Last active
December 7, 2016 15:36
-
-
Save gaplo917/77d7ee9f48ed20f4a60bc20a1b39a2e6 to your computer and use it in GitHub Desktop.
Kotlin Null Safe Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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