-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03nullsafetyExample.kt
40 lines (25 loc) · 1.2 KB
/
03nullsafetyExample.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import kotlin.system.exitProcess
/*
One major part of Kotlin is, that you mostly can get ride of null pointer exceptions as kotlin supports
non nullable reference types. By default when defining variables or constants they cannot be null
*/
fun main(args: Array<String>) {
// the following line will create a compiler error
// val a : Int = null
// If you need to assign null to a variable (I'm leaving constants out because that makes no sense)
// you need to add a question mark to indicate that a variable can be nullable
val b : Int? = null
println("The value of b is $b")
val c1 = Car(null)
val c2 : Car? = null
val brand1 = c1.brand
// val brand2 = c2.brand // this will create a compiler exception because I do not check if the variable is possibly null
// to correctly retrieve the value for the brand, you need to add the "?" sign to perform a null check
val brand2 = c2?.brand
/*
if you want to risk a null pointer exception to be thrown you can use the "!!" operator
I got no example for this being a good practice
*/
//val brand3 = c2!!.brand // uncomment this line to throw a null pointer exception
}
class Car(var brand: String?)