In this article I will try to map methods of Java’s Optional to Kotlin’ssimilar scattered language features and built-in functions. The code in the examples is written in Kotlin, because the language has all the JDK classes available.
Representation
Let’s start with the representation. The Opitonal usage, requires creating a new object for the wrapper every time some value is wrapped or transformed to another type, with exclusion of when the Optional is empty (singleton empty Optional is used). In Kotlin there is no additional overhead, lanuage uses plain old null. The code below shows both approaches:
Map using method of inner value’s type
To transform the value inside Optional using the inner value’s method we can apply a method reference to map. To do the same in Kotlin, we can use safe call operator .? as demonstrated below:
Map using external mapper
If the transformation cannot be performed by simple method call then Optional’smap method is happy to take lambda as well. Kotlin provides built-in method let, which we can invoke on any object. In our case we also need to use safe call operator to skip the calculation for null values:
Filter
In Optional, filter allows to remove the value inside, if the provided predicate test returns false. Kotlin offers two built-in functions with this behaviour - takeIf and takeUntil. First is simialar to the Optional’sfilter, second one drops the value if the predicate returns true - opposite to takeIf. Example code:
FlatMap
There is no built-in Kotlin function with the flatMap behaviour because it’s actually not neccassary. Nullability is not represented by a type and simple mapping turns out to be working fine.
IsPresent
In Kotlin this check can be performed by a simple null comparision:
It is worth to know, that after we do this, compiler is sure that the value is present and allows us to drop all required null checks in the further code (String? becomes String).
Get
Both Optional and Kotin approaches discourage users from getting the inside value with the straight call, because it may cause NPE. Kotlin introduces rude !! operator, which you should use only as a last resort:
OrElse/OrElseThrow
Kotlin introduces elvis operator ?: which allows to set the default value in case of null or throw an excepcion:
Conclusion
I hope reading this article will help you laverage your Optional's experience to quickly learn Kotlin'snull safety features. I think it is worth to give Kotlin a try if only to expand your programming horizonts.
Add a comment