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

diesieben07

09/10/2017, 10:54 PM
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

mersan

09/10/2017, 10:56 PM
I thought its something related to generics
d

diesieben07

09/10/2017, 10:58 PM
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

mersan

09/10/2017, 11:07 PM
thank you again for explaining it 🙂
2 Views