Hello. I have a question regarding the compatibili...
# stdlib
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> getNullId() {
        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().getNullId()

    // 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 🙂
If this is not the place to post, please point me to the right channel.
j
I would recommend #getting-started
🆗 1
s
Thanks. I'll post to that channel 🙂
j
👍 it has to do with something called "platform types" which someone will point you to. it's a compromise, basically.
thank you color 1
s
I'll check the document. Thanks for your kind guidance kodee greetings
k
Platform types are denoted in the IDE as
SomeType!
and nullability enforcement from the kotlin side doesn't apply. Unless the Java interface is annotated with something like
@NonNull
or
@Nullable
I usually try to hedge against these problems by always treating the types as nullable.
👀 1
So in your example the type you're dealing with is
List<String!>
but it would be safer to treat it as
List<String?>