Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dvt32/91501a74065f61b01ff98d07ad813ae1 to your computer and use it in GitHub Desktop.
Save dvt32/91501a74065f61b01ff98d07ad813ae1 to your computer and use it in GitHub Desktop.
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