5/13/2023 0 Comments Kotlin nullable types![]() ![]() ![]() To define a collection of nullable types in Kotlin, we have to append question mark(?) to the type declaration: val countries: List = listOf("India", null, "Germany", "Russia", null) Kotlin collections are non-nullable by default. We should always try to use safe call operator in such cases to ensure NullPointerException doesn’t occur: country?.city?.code Nullability in Collections We should avoid using multiple non-null assertions like the following since it makes it harder to debug which property is null: country!!.city!!.code The not-null assertion operator should be used carefully since it’s a potential sign of a NullPointerException. However, if the reference has a non-nullable value, then it is executed successfully: val country: String? = "India" val result : Int = country!!.length assertEquals(5, result) Let’s look at an example: val city: String? = "Kolkata" return if (city != null) Depending on the complexity of the conditions, this can also lead to nested expressions. This option works only where the variable is immutable. We can use the if-else expression to explicitly check for nullable variables. Let’s look at the different ways how we can handle null references safely in Kotlin. Otherwise, it will throw a compilation error since Kotlin knows that the variable contains null references: val a : String = country.length val b : String = city.length //compilation error ![]() However, in the case of nullable variables, we need to handle the null case explicitly. We can call a method or access a property on a non-nullable variable. To define a nullable variable, we must append a question mark(?) to the type declaration: var city: String? = "Kolkata" city = null We cannot assign a null value to a variable because it’ll throw a compilation error: var country: String = "India" country = null //compilation error In Kotlin, all variables are non-nullable by default. It distinguishes between nullable and non-nullable references as a part of its type system. Kotlin aims at eliminating the risk of NullPointerException. It has been referred to as a billion-dollar mistake. In this article, we’ll look into the null safety in Kotlin.Īny programming language which has the concept of null reference throws a NullPointerException. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |