Last active
January 15, 2017 17:21
-
-
Save gaplo917/b05434e171699998248e30b3fcbfcdfe to your computer and use it in GitHub Desktop.
Kotlin Nullable Type zero overhead
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 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