I have recently started playing with JodaTime within Kotlin an noticed some behaviour that seems odd. All the calls to JodaTime (DateTime.now() etc.) all return Nullable objects. This is a bit annoying because it breaks any of my extension methods that expect DateTime. For example the following function does some assertions on a DateTIme class,
fun Expectation<DateTime>.toBeOnOrBefore(val date: DateTime) : ExpectationChain<DateTime> {
val targetJustDate = target.toDateMidnight() as DateMidnight
val dateJustDate = date.toDateMidnight() as DateMidnight
Unfortunately, when using existing Java APIs, it’s not easy to be sure that specific method cannot return null. That’s why all methods are treated as returning/taking nullable types. If you sure that specific API method doesn’t return null, you can use “!!” postfix operator, e.g.:
DateTime.now()!!
Of course, it’s not very convenient, and it makes the code pretty dirty, but now it’s the easiest solution. It is expected that in next Kotlin milestone you will be able to define Kotlin signatures for existing APIs method using external annotations. So you’ll only have to declare that DateTime.now() cannot return null only once.
In future, we are going to add bytecode analyzer which would detect methods which can’t return null or parameters which cannot be null, so in some cases Kotlin signatures for existing APIs will need less manual work.