Preferences

Making it an expression would indeed by nice - I do like that in Kotlin, though it's still not particularly short there (but given that there are not really checked throws there, it's easy to just have a lambda for that).

I believe there was a proposal to incorporate it into the switch expression? That may make it slightly too complex though, with null handling and pattern matching.


Yes there was a proposal by Brian to make it into a switch expression: https://www.hackerneue.com/item?id=40088719, though that draft is already 1.5 years old and I don't expect it to be delivered anytime soon. It would alleviate some pain, but I really think we need something like try! to escape the compiler when some errors aren't possible:

    A a;
    try {
      a = someThrowingFn();
    } catch (AException ex) {
      throw new IllegalStateException(ex); // not possible
    }
becomes

    var a = try! someThrowingFn();
or with Brian's proposal:

    var a = switch (someThrowingFn()) {
        case A anA -> anA;
        case throws AException ex -> throw new IllegalStateException(ex);
    }
    
...still a bit verbose and funky

You should check out Kotlin's proposal for error unions, I think it's pretty good and prevents a lot of boiler plate associated with results/exceptions: https://github.com/Kotlin/KEEP/blob/main/proposals/KEEP-0441.... They propose a similar construct to try! with !! like they have for nullable types.

This item has no comments currently.