Created
August 21, 2022 11:27
-
-
Save dvt32/91501a74065f61b01ff98d07ad813ae1 to your computer and use it in GitHub Desktop.
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
class MyClass { // This is very helpful for preventing NPEs more easily. | |
var field1: String = "hello" // null value NOT allowed | |
var field2: String? = null // null value allowed | |
fun myMethod() { | |
// field1 = null // COMPILER ERROR | |
field2 = "world" | |
field2 = null | |
} | |
fun myMethod2() { | |
// println(field2.length) // COMPILER ERROR | |
// "Safe call" ( ?. ) | |
val len = field2?.length // null if field2 is null (otherwise equal to field2's length) | |
println(len) | |
/* | |
Note: if we have a chain such as "bob?.department?.head?.name", | |
the chain will return null if any of the properties are null. | |
*/ | |
// "Elvis operator" ( ?: ) | |
val myString = field2 ?: "some value" // "Give me field2's value if it's not null, otherwise use another value" | |
val myStringLength = field2?.length ?: 5 | |
// "Asserted call" ( !! ) | |
val lengthOfField2 = field2!!.length // "I'm sure field2 is NOT null and even if it is, I'm OK with getting a NPE" | |
// Smart cast | |
val str: String? = null | |
// println(str.length) // COMPILER ERROR | |
if (str != null) { | |
// If "str" is not null, Kotlin automatically knows that it will have "length", lowercase(), etc. | |
println("${str.length} ${str.lowercase()} ${str.uppercase()}") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment