This site uses cookies to analyze traffic and improve service.

By using this site, you agree to this use. See details.

Kotlin Tour


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content


Nullable types

All types in Kotlin are non nullables (they don't include the null value).
To do so the type must be explicitly marked as nullable with the ? sign.

Declare a String variable called name and set it to the null value
val name: Unit = TODO()

Safe calls

Calling a function on a nullable value might raise a NullPointerException.
Thanksfully Kotlin has a safe call operator : ?.

Declare a nameLength variable holding the length of the name String. What is its type ?
val nameLength: Unit = TODO()


What if we don't want to stay in the dangerous nullable world and escape from it ?
We can thank Elvis for that and use the operator ?: allowing to specify a non-null value to use in case the value is null.

Declare a length variable holding the length of the name String, 0 if name is null
val length: Unit = TODO()

I ❤️ (K)NPE

Finally if really we want to raise a NullPointerException we can use the !! operator.

Declare a function npe returning the length of the given String, throwing a NullPointerException if the string is null
fun npe(s: String?): Int = TODO()


In Kotlin the keyword as is used to cast an object into a specific type. If the cast fail a ClassCastException is raised, as? can be used to return a null value if the cast failed.

Smart casts

Using the operators is and !is we can check if an object is of a given type. What's really nice is that with smart casts the compiler infer the type of our object after these operators.

Implement a function smartadd that can add String or Int and throw a IllegalArgumentException otherwise
fun smartadd(a: Any, b: Any): Int = TODO()
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content