2 ms·
Even in lowly Java, they later added to Optional the orElseThrow() method since the name of the get() method did not connote the impact of unwrapping an empty O
by shadowmatter 1y ago
Even in lowly Java, they later added to Optional the orElseThrow() method since the name of the get() method did not connote the impact of unwrapping an empty Optional.
- vbezhenar 1y agoI've found both methods very useful. I'm using `get()` when I've checked that the value is present and I don't expect any exceptions. I'm using `orElseThrow()` when I actually expect that value can be absent and throwing is fine. Something like if (userOpt.isPresent()) { var user = userOpt.get(); var accountOpt = accountRepository.selectAccountOpt(user.getId()); var account = accountOpt.orElseThrow(); } Idea checks it by default and highlights if I've used `get()` without previous check. It's not forced at compiler level, but it's good enough for me.
- loglog 1y agoWhile the `Optional` API is generally pretty inconvenient (compared e.g. to Kotlin), it does offer the more precise `ifPresent`.
- vbezhenar 1y agoJava lambdas are terrible so I usually avoid them. There's no reason to invent new methods, when language already has corresponding statements.