

In contrast, using the Optional type in a non-safe way is not checked by the compiler, and will lead to a runtime exception. Using them in a non-safe way will lead to a compile-time error. Second, nullable types in Kotlin provide null-safety at compile-time. Unlike Optional, no wrapper object is created for wrapping the actual value.

Using them leads to short, concise, and readable code, especially when combined in longer call chains.īesides the more readable code, Kotlin’s nullable types have several advantages over Java’s Optional type.įirst, there is no runtime overhead involved when using nullable types in Kotlin¹. Kotlin provides a range of built-in operators and stdlib functions that simplify handling of nullable types. In Java, an Optional property can be declared as follows: public interface Person Conclusion Using nullable types in properties or as the return type of functions is considered perfectly valid and idiomatic in Kotlin. Fortunately, in Kotlin there is no arguing about it. Optional/Nullable Properties and Return Typesĭepending on whom you ask, using Optional as the type of a field or return type is bad practice in Java.

Prior knowledge about both Optional and nullable types is assumed. In this post we will see how the Optional type compares and translates to nullable types in Kotlin.

Kotlin natively supports nullable types, making the Optional type, as well as all the API it provides, obsolete. Initially I was surprised that Kotlin did not embrace the Optional type like Scala did. When I learned about Kotlin last year, it seemed to have some similarities to Scala, making me very excited. I already knew about the Optional type from various adventures into functional programming languages and knew of its powers. When Java 8 introduced the Optional type many years ago, I was happy like a bird.
