Is there a way to tell the Kotlin compiler to trea...
# announcements
r
Is there a way to tell the Kotlin compiler to treat certain Java methods with a
void
return as
Nothing
instead of
Unit
?
I don't believe there is (without wrapper functions), but I figured I'd ask in case I'm missing something.
b
That would break the type system.
void
is isomorphic to
Unit
- they are both sets with exactly one element - whereas
Nothing
is a set with zero elements. There would be no way for Java to interoperate with Kotlin if
Nothing
was used in place of
void
.
r
I only meant one way, so in my Kotlin code I tell it "this function from this library never returns". I don't need Java to know anything about it.
b
The type checker needs to be able to understand it and they are fundamentally different types
r
Yes, but I don't see how that's an issue. You can already use things like annotations (even external annotations) to modify compilation. Why not to say "this is a divergent code path"?
b
Eh, my guess is writing something to handle that special case of Java not really having an official Nothing type wasn't a high priority for the Kotlin roadmap
r
That's fair
b
Strangely enough it's possible to express what you want in Kotlin with enough function wrapping, although IJ warns that the call is "unreachable code"
r
It doesn't take all that much.
Copy code
inline fun diverge(op: () -> Unit): Nothing {
    op()
    error("Cannot be reached")
}
b
That seems like an easier solution than adding exceptions to the type system
r
I didn't need it in the type system. Just something that would work like external annotations and would interpreted by the compiler.