https://kotlinlang.org logo
#announcements
Title
# announcements
r

Ruckus

07/19/2019, 8:01 PM
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

Bob Glamm

07/19/2019, 10:07 PM
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

Ruckus

07/19/2019, 10:10 PM
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

Bob Glamm

07/19/2019, 10:14 PM
The type checker needs to be able to understand it and they are fundamentally different types
r

Ruckus

07/19/2019, 10:24 PM
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

Bob Glamm

07/19/2019, 10:35 PM
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

Ruckus

07/19/2019, 10:35 PM
That's fair
b

Bob Glamm

07/19/2019, 10:36 PM
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

Ruckus

07/19/2019, 10:38 PM
It doesn't take all that much.
Copy code
inline fun diverge(op: () -> Unit): Nothing {
    op()
    error("Cannot be reached")
}
b

Bob Glamm

07/19/2019, 10:38 PM
That seems like an easier solution than adding exceptions to the type system
r

Ruckus

07/19/2019, 10:39 PM
I didn't need it in the type system. Just something that would work like external annotations and would interpreted by the compiler.
4 Views