In this case, nullableValue is assigned a null value. Val nonNullValue: Int = nullableValue!! // Throws NullPointerException Since we have asserted non-nullability, the compiler treats nonNullString as a non-null value, allowing us to call methods on it without null safety checks. However, by using the "!!" operator, we assert that the value is not null and assign it to nonNullString. In this example, nullableString is explicitly declared as nullable ( String?). Println(nonNullString.length) // The compiler treats nonNullString as non-null Val nonNullString: String = nullableString!! // Asserting non-nullability Example 1 val nullableString: String? = "Hello" It bypasses the null safety checks provided by Kotlin, so it should be used with caution and only when you are certain that the value is not null. However, it's important to note that using !! can be risky because if the value is actually null at runtime, a NullPointerException will be thrown. The operator instructs the compiler to treat the expression as non-null, even if its type is nullable. The purpose of the double exclamation mark ( !!) in Kotlin is indeed the "not-null assertion operator." It is used to assert that a nullable expression is not null. For more information, read our affiliate disclosure. If you click an affiliate link and subsequently make a purchase, we will earn a small commission at no additional cost to you (you pay nothing extra). Important disclosure: we're proud affiliates of some tools mentioned in this guide. If the value happens to be null, a NullPointerException will be thrown at runtime. When you use the !! operator on a nullable variable or expression, you are telling the compiler that you are certain that the value is not null at that particular point in the code. In Kotlin, the double exclamation mark ( !!) is called the "not-null assertion operator." It is used to assert that a nullable expression is not null, and it instructs the compiler to consider the expression as non-null. Keep laughing and enjoy your coding journey!□□ Why did the Kotlin developer bring a flashlight to work?īecause they heard Kotlin had a lot of "smart casts"!
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |