Kotlin null default value5/24/2023 Notice that no exceptions are thrown in the REPL when you declare a nullable type: > var s: String? = nullĪlso notice that I intentionally declare those variables as var fields. This simple addition to your type allows your variable to contain null values. You declare a type to be nullable by adding a question mark after it: var s: String? = null Similarly, variables that are instances of custom types can’t be null either: > class Person (var name: String)Įrror: null can not be a value of a non-null type Line_3.PersonĪ nullable type is a variation of a type that permits null values. Variables that are instances of standard Kotlin types can’t contain null values: val> val s: String = nullĮrror: null can not be a value of a non-null type StringĮrror: null can not be a value of a non-null type Int I use String in those statements, but the same things can be said about every other type, including Int, Float, Person, etc. The operations that can be performed on nullable types are very limited.A variable of the nullable type String? can be null.A variable of type String can never be null.Nullable types are an approach in Kotlin to help you eliminate null values and null pointer exceptions (the dreaded NullPointerException).
0 Comments
Leave a Reply. |