Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active December 7, 2016 15:36
Show Gist options
  • Save gaplo917/77d7ee9f48ed20f4a60bc20a1b39a2e6 to your computer and use it in GitHub Desktop.
Save gaplo917/77d7ee9f48ed20f4a60bc20a1b39a2e6 to your computer and use it in GitHub Desktop.
Kotlin Null Safe Example
// Kotlin null safe example
// Java null risk example https://gist.github.com/gaplo917/5dc037bedea39a348854ae59ba89c063
fun doSth(str: String): String {
return str.toLowerCase()
}
fun doSthOptional(str: String?): String? {
// Optional chainning, similiar to Swift
return str?.toLowerCase()
}
doSth(null) // compile error
doSth("Abc") // return "abc"
doSthOptional(null) // return null
doSthOptional("Abc") // return "abc"
// More example on copmile-time checking
var a0 // fail, compile error
var a1 = null // fail, compile error
var a2: String = null // fail, compile error
var a3: String? = null // OK
println(a3) // OK, print null
println(a3.toLowerCase()) // fail, compile error
println(a3?.toLowerCase()) // OK, print null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment