

To do the same in Kotlin, we can use safe call operator (?.) as demonstrated below: val lengthKotlin: Int? = kotlinNullable?.length To transform the value inside Optional using the inner value’s method we can apply a method reference to map. Map Using The Method of The Inner Value’s Type Val javaNullable: Optional = Optional.ofNullable("Java way, can be null as well”) The code below shows both approaches: val kotlinNullable: String? = "Kotlin way, this can be null" In Kotlin, there is no additional overhead. Optional usage requires creating a new object for the wrapper every time some value is wrapped or transformed to another type - with the exclusion of when the Optional is empty (singleton empty Optional is used). The code in the examples is written in Kotlin because the language has all the JDK classes available. To define a nullable variable, we must append a question mark(?) to the type declaration: fun main() ") // Throws NullPointerExceptionĮxception in thread "main" kotlin.In this article, I will try to map methods of Java’s Optional to Kotlin’s similar, scattered language features and built-in functions.

Here, by default compiler considers name variable as a Non-Null reference. Output: Error:(6, 27) Kotlin: Null can not be a value of a non-null type String Var name:String = null // COMPILATION ERROR We cannot assign a null value to a variable because it’ll throw a compilation error( NPE): In Kotlin, all variables are non-nullable by default.

Let’s understand with simple example in Java where NullPointerException occurs: In Java this would be the equivalent of a NullPointerException or NPE. One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception. Null Safety in Kotlin is to eliminate the risk of occurrence of NullPointerException from code.
