Interop with third party Java libraries - threeten backport


#1

I'm using the ThreeTen Java 7 backport in my project (http://threeten.github.io)

The API is beautiful but unfortunately it makes heavy use of factory methods that are not marked @NotNull.  This makes the API very difficult to use with Kotlin.

For example:

  fun hello() {
  val today = LocalDate.now()


  val tomorrow = today.plusDays(1)
  }

Here, LocalDate.now() always return a non-null object, but unfortunately since this is a Java library the type of today is the nullable “LocalDate?”.  So, today.plusDays is an error.  I tried using LocalDate!!.now(), but IntelliJ marks this as an error as well: “LocalDate does not have a class object”.  I realize now it was probably stupid of me to try using the !! here as it’s not an instance  :)   My temporary solution was to forcefully cast it as LocalDate:

  fun hello() {
  val today = LocalDate.now() as LocalDate


  val tomorrow = today.plusDays(1)
  }

…but this is not really a solution (tomorrow is still of type “LocalDate?” and casting here is probably a poor practice).  The ThreeTen backport source code is on github, so I suppose I can fork it and add NotNull annotations.  Is there an alternative approach I can use other than using the !! operator all over the place?

Thanks!


#2

Instead of a cast, you can say

  fun hello() {   val today = LocalDate.now()!!

  val tomorrow = today.plusDays(1)
  }


or

  fun hello() {   val today = LocalDate.now()

    val tomorrow = today!!.plusDays(1)

  }


Also, consider using KAnnotator or annotating the factory methods as @NotNull using intentions in IntelliJ


#3

Thanks, I took a look at KAnnotator.  It looks perfect, thanks.