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

Try to stick a function that may fail into a higher order function. The best example would be .map on streams/collections.

You can only do it with unchecked exceptions in Java. In Rust, you can transparently do it with iterators and the result type.

So given xs: [A] and f: A -> Result<A, E>, it is trivial to typesafely get Result<[A], E> by xs.map(f) where map: forall T. [T] -> (T -> S) -> [S]. This is outright impossible with Java. You have to circumvent the type system, or emulate Rust's approach.



Maybe I'm missing something but why does this not work with Java?

Is it the fact you would put your xs.map call in a mapper or something?

Because I know for sure you can do it in Kotlin: https://github.com/michaelbull/kotlin-result

But I don't see reified generics as a requirement for what you describe, and that's the main Kotlin-only feature I see being used


The idiomatic error handling mechanism of Java is the checked exception. This mechanism does not work with higher order functions.

You can emulate Rust's approach with Java, by creating what is essentially a sum type like Result. You'd have to enforce that any access to its content must also handle the error case, and I don't really know how to do that generally. There are various hacks, like having a bespoke sum type for that particular operation that twrows a particular exception on access to its content. But that gets really old, really fast.


Kotlin doesn't have checked exceptions, so being able to do it in Kotin is irrelevant.


What?

a) I asked how is it not possible in Java. The Kotlin library is just an example of something I use, it's not relying anything impossible in Java as far as I can tell... like I said reified generics don't change what the calls would look like, just what the implementation looks like

b) What do checked exceptions have using Result? The whole point is you use Result monads in all your code instead of exceptions. When interfacing with legacy code you wrap any exceptions in a Result class as well.




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

Search: