Best practice for annotating java methods that potentially return null (@Nullable on java method seems to be ignored?)

Hi,

Are there best practices for adding annotations onto java methods that can return null such that Kotlin treats them as nullable.  

I have tried using org.jetbrains.annotations.Nullable … and this gives the expected warnings when Java code uses the method (uses the response of the method without checking it is null) … however, I am not seeing the expected warnings with Kotlin code using the method (the return type is considered not nullable).

I think I am all up to date - I’m using Kotlin compiler 0.12.1218  , javac 1.8.0_45

Any pointers would be helpful.

Thanks, Rob.

Could you share a small code example (both Java and Kotlin)?

Java Nullable method:

  @Nullable
  public T byId(I id) {
  return db().find(type, id);
  }

Kotlin use:

  val nz = Country.byId(“NZ”)
  nz.name = “something”

  // I expect this to complain … but nz is considered to be Country! and not Country?
  // when I ctrl-hover over the method I see “Nullable public open fun byId(id:String!): Country!”
  // byId() is coming off a companion object but that does not seem to make any difference, other nullable no companion method usage is similar.

Java use:

  Country nz = Country.find.byId(“NZ”);
  nz.setName(“something”);

  // the use of nz without a check for null gives me a warning (so as expected - all good)

Cheers, Rob.

There is a bug in latest release build with nullability warnings when return type is generic parameter. It has been fixed in our production branch (more precisely your usage becomes an error instead of warning), these changes will be included in M13 release.

Thanks.