In Kotlin: `String` can never be null, `String?` c...
# announcements
d
In Kotlin:
String
can never be null,
String?
can. In Java
String
does not express any notion of whether or not it can be null.
m
I thought its something related to generics
d
So, in your example with the
anyKotlin
method, if the compiler infers
String
for
T
, it assumes "hey this method cannot return null now!". And since
anyKotlin
is written in Kotlin, the compiler "trusts" it (not sure of the exact rules here). Inside
anyKotlin
, the compiler cannot insert any null checks after the Java method returns, since it does not know what
T
actually is,
T
might be
String?
in Kotlin, which then means that it can be null, so a null check would not be correct. So there cannot be any checks here.
👍 1
If
anyKotlin
had a non-generic return type (or you did
T : Any
so that
T
can never be a nullable type) then the compiler could insert the null check.
m
thank you again for explaining it 🙂