Nullable Type in Kotlin

Level 286 keystrokes

Declares a nullable String and checks it for null before using it.

Kotlin code

// The ? in String? means the variable may hold null
1val text: String? = null
// Check for null before using the value
2if (text != null) {
// Smart cast: inside this branch text is treated as String
3 println(text)
4} else {
// text is null, so this branch runs and prints Empty
5 println("Empty")
6}

Output

Empty
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
  • "× 2
  • {× 2
  • }× 2
  • =× 2
  • :× 1
  • !× 1
  • ?× 1

More Kotlin examples at level 2

← Kotlin typing practice