![]() ![]() You’ve already seen variable assignment: var s: String? = null Converting a nullable type to its non-nullable equivalent.You’ll use and encounter nullable types in several areas: Allowing null values in your code is considered a “bad smell.” (When I look at code that permits null values I think, “How quaint, this is like code from 1996.”) Places where you’ll use nullable types The ? operator says, “This instance of this type is allowed to contain a null value.”Īs mentioned in the previous chapter, you should write your code to never use null values. A nullable type is a variation of an existing type, and can contain a null value.Default Kotlin types cannot contain null values.I do this because they’re declared with null values, but at some point later in their lifetime they’ll presumably contain more useful values. ![]() 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.
0 Comments
Leave a Reply. |