Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Created November 17, 2019 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magdamiu/83f12f3f3b8ec23db3a954c5174f8b8e to your computer and use it in GitHub Desktop.
Save magdamiu/83f12f3f3b8ec23db3a954c5174f8b8e to your computer and use it in GitHub Desktop.
null safety with conditional if
// check for null in conditions
val trainingName: String? = "Learn Kotlin in 45 minutes"
if (trainingName != null && trainingName.isNotEmpty()) {
print("String of length ${trainingName.length}")
} else {
print("Empty string")
}
val platform: String? = null
val language = "Kotlin"
println(platform?.length) // safe call
println(language.length) // unnecessary safe call
val lengthOfWord = platform!!.length // !! operator
val numberOfLetters: Int? = lengthOfWord as? Int // safe cast
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment