Safe Call Operator in Kotlin

Level 3122 keystrokes

Uses the safe call operator ?. to call a method and read a property on a nullable String.

Kotlin code

// A nullable String that currently holds a value
1val text: String? = "Hello Kotlin"
// ?. calls uppercase() only if text is not null; otherwise the result is null
// upper has type String?
2val upper = text?.uppercase()
// Safe call on a property: length is an Int? (here 12)
3val length = text?.length
4
// Prints HELLO KOTLIN
5println(upper)
// Prints 12
6println(length)

Output

HELLO KOTLIN
12
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • ?× 3
  • (× 3
  • )× 3
  • =× 3
  • .× 2
  • "× 2
  • :× 1

More Kotlin examples at level 3

← Kotlin typing practice