Support for or(o: T) for nullable types?


#1

One thing I've come to love when using Google Guava's Optional<T> class is the #or() method.  Where I can easily get the value in the option OR some other/default value.  i.e.

  DateTime lastDateTime = (user.getLastLoginDate().or(new DateTime().minusWeek(1))

I was wonder if there was a suitable alternative in Kotlin, nullable types have a #sure() method to get the non-nullable version, I was wondering if it would be good to have something like #or() here as well in Kotlin?  Or if there was a preexisting solution?

Given that if is an expression, I was thinking I could just use that, but I’m not sure what I’d put in the if - doing “== null” feels wrong given we have nullable types…


#2

I wondered this too a little while ago - turns out Kotlin has the ?: operator that works like that (and the right hand expression is evaluated lazily):

val lastDateTime = user.getLastLoginDate ?: DateTime().minusWeek(1)

If you are working with collections you can use the helper function orEmpty() to ensure you have a valid collection (converting null to the empty list); other extension functions are available on collections too.


#3

Awesome ;-) I suspected there might be something like that.

+1 will compile again.