官术网_书友最值得收藏!

Null safety

Generally, when we write code, we declare the fields in a class. We are not sure whether or not the field is initialized during execution. To find out, we use null checks and annotations such as @Nullable or @NotNull. Kotlin provides elegant syntax for declaring fields with nullable and non-nullable types, which prevents the problem of accidental NullPointerExceptions (NPEs). Kotlin catches possible null pointers when the code is being compiled, meaning that no null pointer issues will occur after the application has been deployed. This means that there are almost no cases of NullPointerException.

Consider the following code:

object NullabilityTest {
    @JvmStatic
    fun main(args: Array<String>) {
        var msg: String = null
        println(msg)
    }
}

Let's compile the preceding code:

[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.2.41:compile (compile) on project myJavaApp: Compilation failure
[ERROR] ..\Intermixing Java and Kotlin\myJavaApp\src\main\java\NullabilityTest.kt:[10,28] Null cannot be a value of a non-null type String

This code gives a compilation error. If we want to assign a null value to a variable, it has to be declared as follows:

var msg: String ?= null

The msg variable can be declared with a null value. Let's consider another example:

object NullabilityTest {
    @JvmStatic
    fun main(args: Array<String>) {
        var userList:ArrayList<String> ?= null
println(userList.get(0)) } }

Variables can be declared to hold a null value. If we invoke any function on these variables, such as userList.get(0)it doesn't throw NullPointerException at runtime. Instead, it just fails to compile:

Error:(6, 25) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.collections.ArrayList<String>? /* = java.util.ArrayList<String>? */

Kotlin catches possible null pointers during compile time. It warns us that we should initialize the var before accessing it. The language provides clear constructs to define which variables can hold a null value, and which can hold a non-null value. When a variable is null, the language provides a safer way to deal with it, avoiding null pointer issues at runtime. This means that there are almost no cases of NullPointerException.

Since the variables have been declared to hold a null value, we need to perform a null check before accessing any function on this variable. Kotlin provides an elegant syntax for null check (?.), as follows:

userList?.get(0)

Kotlin provides an elegant syntax to perform an operation on the variable that can hold null values safely. Consider the following code:

fun main(args: Array<String>) {
    var userList:ArrayList<String> ?= null
var user = userList?.get(0) user ?.let { println("got the user details") } ?: run { println("there is no user") } }

Here, we create a list of users, userList, and try to get the first object and do something with it. In this case, the user instance is null, so when we use ?. on it, it doesn't throw NullPointerException. If the  user instance is not null, it prints a got the user details message to the console. If it is null, it prints a there is no user message.

In short, Kotlin is a feature-packed language, with its simple and concise language constructs. If we already have an application written in Java, we can include Kotlin to get the benefits that it offers. Once the code is compiled, everything is bytecode and no distinction is made between Java or Kotlin. This is possible because Kotlin is interoperable with Java and provides an elegant way of writing code that reduces the development life cycle and is less error prone.

主站蜘蛛池模板: 巴林左旗| 衡水市| 西和县| 丰原市| 扶绥县| 漳平市| 和田市| 德令哈市| 鹿邑县| 保定市| 南召县| 乐山市| 新巴尔虎左旗| 增城市| 万州区| 余庆县| 峨眉山市| 个旧市| 家居| 洛浦县| 肇源县| 天祝| 平罗县| 额尔古纳市| 杨浦区| 蚌埠市| 正镶白旗| 醴陵市| 永登县| 元朗区| 施秉县| 大荔县| 青铜峡市| 柳河县| 大渡口区| 洛宁县| 浦县| 肃北| 肇东市| 外汇| 浙江省|