- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 331字
- 2021-07-02 18:48:34
Not-null assertion
Another tool to deal with nullity is the not-null assertion operator. It is represented by a double exclamation mark (!!). This operator explicitly casts nullable variables to non-nullable variables. Here is a usage example:
var y: String? = "foo" var size: Int = y!!.length
Normally, we would not be able to assign a value from a nullable property length to a non-nullable variable size. However, as developers, we can assure the compiler that this nullable variable will have a value here. If we are right, our application will work correctly, but if we are wrong, and the variable has a null value, the application will throw NullPointerException. Let's examine our activity method onCreate():
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val locked: Boolean = savedInstanceState!!.getBoolean("locked") }
The preceding code will compile, but will this code work correctly? As we said before, when restoring an activity instance, savedInstanceState will be passed to the onCreate method, so this code will work without exceptions. However, when creating an activity instance, the savedInstanceState will be null (there is no previous instance to restore), so NullPointerException will be thrown at runtime. This behavior is similar to Java, but the main difference is that in Java accessing potentially nullable objects without a nullity check is the default behavior, while in Kotlin we have to force it; otherwise, we will get a compilation error.
There are only few correct applications of this operator, so when you use it or see it in code, think about it as a potential danger or warning. It is suggested that not-null assertion should be used rarely, and in most cases should be replaced with safe call or smart cast.
In this case, there is no point in using the not-null assertion operator because we can solve our problem in a safer way using the let function.
- Java語(yǔ)言程序設(shè)計(jì)
- SPSS數(shù)據(jù)挖掘與案例分析應(yīng)用實(shí)踐
- Visual C++程序設(shè)計(jì)教程
- 密碼學(xué)原理與Java實(shí)現(xiàn)
- Rust編程從入門到實(shí)戰(zhàn)
- Java編程指南:基礎(chǔ)知識(shí)、類庫(kù)應(yīng)用及案例設(shè)計(jì)
- SEO實(shí)戰(zhàn)密碼
- Linux命令行與shell腳本編程大全(第4版)
- Expert Data Visualization
- RabbitMQ Cookbook
- PLC應(yīng)用技術(shù)(三菱FX2N系列)
- Mastering Xamarin.Forms(Second Edition)
- Django 5企業(yè)級(jí)Web應(yīng)用開發(fā)實(shí)戰(zhàn)(視頻教學(xué)版)
- 編程改變生活:用Python提升你的能力(進(jìn)階篇·微課視頻版)
- 打造流暢的Android App