Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.




I'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.

While the `Optional` API is generally pretty inconvenient (compared e.g. to Kotlin), it does offer the more precise `ifPresent`.

Java lambdas are terrible so I usually avoid them. There's no reason to invent new methods, when language already has corresponding statements.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: