Optionals in Kotlin

In No more Ifs I wrote a little bit about the new Optional class in Java 8. It enables the developer to work with optional values without a complex nested structure of if-then-else expressions. A colleague of mine, being a big fan of Kotlin, dropped a hint that using Kotlin, it would be much easier. He could even prove it. 🙂

In the blog article I used an example of parsing a list of parameters for a float value. The parameters were given as a map from a key to a value. To parse the parameters, you have first look for the key, then check if it is mapped to a unique value and finally convert the string value to a float. Every step can fail and lead to no result value. This is an implementation using Java in combination with Vavr:

Option<Float> readFloatParameterUsingOption(
                    String parameterName,
                    Map<String, Set> parameters) {
  return Option.of(parameters.get(parameterName))
               .filter(values -> values.size() == 1)
               .map(values -> values.iterator().next())
               .flatMap(Function1.lift(Float::parseFloat));
}

Kotlin has a built-in operator .? that evaluate its right part only if the left part is not null. If the left part is null, the expression is evaluated to a null value. In combination with the standard library of Kotlin and the [] syntax to access maps, the same algorithm can be written as:

fun readFloatParamK(
   name: String,
   params: Map<String, Set>): Float? =
        params[name]
                ?.run { if (size != 1) null else this }
                ?.first()
                ?.toFloatOrNull()

This is IMHO a well readable and concise way of writing the algorithm and, thus, another argument to use Kotlin.

You can find the Java and the Kotlin code here:
https://github.com/akquinet/NoMoreIfs