Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active January 15, 2017 17:21
Show Gist options
  • Save gaplo917/b05434e171699998248e30b3fcbfcdfe to your computer and use it in GitHub Desktop.
Save gaplo917/b05434e171699998248e30b3fcbfcdfe to your computer and use it in GitHub Desktop.
Kotlin Nullable Type zero overhead
// Kotlin NullableType is different from java.util.Optional or scala.Option
// it is NOT a Value Type
var str: String? = null
str == null // Compile OK! => true
str = "gary" // Compile OK!
str == null // Compile OK! => false
str == "gary" // Copmile OK! => true
// Optional chaining
str?.toUpperCase() == "GARY" // Compile OK! => true
str?.toLowerCase()?.capitalize() == "Gary" // Compile OK! => true
// Default value `?:`
val username = str ?: "N/A" // username is String now!
// Kotlin Smart cast - if
if(str is String){
// the Type of str is smart casted to `String`!!!
println(str.toUpperCase())
}
// Kotlin Smart cast - when
when(str){
is String -> println(str.toUpperCase())
else -> println("str is null")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment