Hello. I have a question regarding the compatibili...
# getting-started
s
Hello. I have a question regarding the compatibility between Kotlin and Java. I was wondering if you could shed some light on why the code below is working...
Copy code
// Java
public class TestRepository {
    
    public <T> List<T> getCollectionWhichHasNull() {
        return Collections.singletonList(null);
    }
}

// Kotlin
fun main() {
    // type is List<String>, which means that this collection has non-null value (I think...)
    // There's any compilation error is occurred, why?
    val result: List<String> = TestRepository().getCollectionWhichHasNull()

    // Although result variable's type is List<String>, it contains null item...
    for (s in result) {
        println(s != null) // false
    }
}
If you have any references or blog posts, I'd appreciate it 🙂
e
https://kotlinlang.org/docs/java-to-kotlin-nullability-guide.html#platform-types Kotlin treats Java declarations (that don't have known
Nullable
or
NotNull
annotations) as having "platform types", or unknown nullability. it'll let you treat them as either nullable or non-nullable without warning, and if you assume they're non-nullable you get the same potential for
NullPointerException
as you would in Java.
👀 1
s
Now I understand that because compiler can't identify the type contains null item or not because it does not have some identifier things like
@NotNull
. Thanks for your explanation with document thank you color