Null safety in kotlin8/31/2023 ![]() ![]() More complex conditions are supported as well: if ( b != null & b. The compiler tracks the information about the check you performed, and allows the call to length inside the if. ![]() Checking for null in good old if conditionsįirst, you can explicitly check if b is null, and handle the two options separately: val l = if ( b != null) b. length // error: variable 'b' can be nullīut what if we still need to access property of the variables which are declared as nullable? There are a several ways of doing that. ![]() lengthīut if you want to access the same property on b, that would not be safe, and the compiler reports an error: val l = b. Now, if you call a method or access a property on a, it’s guaranteed not to cause an NPE, so you can safely say val l = a. To allow nulls, we can declare a variable as nullable string, written String?: var b: String ? = "abc" b = null // ok Kotlin’s type system is responsible for this by distinguishing references that can hold nullable references and non-null references.įor example, a regular variable of type String can not hold null: var a: String = "abc" a = null // compilation error Null Safety – one of the biggest features of Kotlin’s, this feature aims to eliminate the danger of null references. ![]()
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |