How to import List<X> from Java without getting List<X!>


#1

Kotlin reference states:

“Java types which have nullability annotations are represented not as platform types, but as actual nullable or non-null Kotlin types.”

I am wondering how to annotate a parameter/result/field of type List in Java such that when imported into Kotlin, it is treated as definitely nullable or non-null.

So:

var x = someJavaObject.someJavaMethod() // returning List<String> in Java
var y = x[0] // I want this to have Kotlin type String, not String!

None of the existing nullness annotations for Java seem to be able to express the nullability of generic type parameters. This could result in imported Java APIs not having as much null-safety in Kotlin as we might hope for.

Comments appreciated.


#2

In Java 8 you can place annotations on type arguments.

You need to add a dependency on the annotation library org.jetbrains:annotations:15.0 which was compiled for java 8 and annotate type argument with @NotNull:

import org.jetbrains.annotations.*;

public class SomeJavaClass {
    public <T> List<@NotNull T> method() {
        // ...
    }
}

Then in Kotlin you’ll see this method returning List<T & Any>, i.e. its argument type will be a non-nullable variant of T.


#3

Iyla,

Thanks for your response :slight_smile:

Is this workable with Android, or does the dependency on Java 8 limit it to non-Android environments?