Package-scope non-null annotation in Java for Kotlin (built by Gradle)

525 views Asked by At

I'm trying to write a Java library that has a non-nullable API, and I'd like Kotlin to properly infer this non-nullability. I'm using JSR-305 annotations and its @TypeQualifierDefault to achieve the effect for the entire package, as per Kotlin's Java interop reference.

I build it all using Gradle 4.10.2 and I supply -Xjsr305=strict to the Kotlin compiler, as instructed. Yet, when I reflectively inspect the types from Kotlin, they are reported as platform types, e.g.:

fun sample.Foo.bar(T!): kotlin.collections.(Mutable)List<T!>!

What am I doing wrong that I don't get the following output?

fun sample.Foo.bar(T): kotlin.collections.(Mutable)List<T>

Note that Spring Framework 5 has a similar annotation named @NonNullApi.

I'm using OpenJDK 11.

PS. I know I can just annotate every method and parameter with @Nonnull, but I'm after global behavior and converting Kotlin's List<T!> to List<T>.


Here's the MCVE:

  • src/main/java/sampleAnnotation/NonNullPackage.java

    package sampleAnnotation;
    
    import javax.annotation.Nonnull;
    import javax.annotation.meta.TypeQualifierDefault;
    import java.lang.annotation.*;
    
    @Nonnull
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PACKAGE)
    @TypeQualifierDefault({
            ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_USE
    })
    public @interface NonNullPackage {
    }
    
  • src/main/java/foo/package-info.java

    @NonNullPackage
    package foo;
    
    import sampleAnnotation.NonNullPackage;
    
  • src/main/java/foo/Foo.java

    package foo;
    
    import java.util.List;
    
    public interface Foo {
        <T> List<T> bar(T t);
    }
    
  • src/main/kotlin/sampleKotlin/Main.kt

    package sampleKotlin
    
    import foo.Foo
    import kotlin.reflect.full.memberFunctions
    
    fun main(args : Array<String>) {
        println(Foo::class.memberFunctions.first())
    }
    
  • build.gradle

    plugins {
        id 'java'
        id 'org.jetbrains.kotlin.jvm' version '1.3.0'
    }
    
    wrapper {
        gradleVersion = '4.10.2'
    }
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compileOnly group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'
    
        compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib'
        compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect'
    }
    
    compileKotlin {
        kotlinOptions.freeCompilerArgs = ['-Xjsr305=strict']
    }
    
0

There are 0 answers