kotlin null

In this tutorial, we’ll look into Kotlin Null Safety. NullPointerException is one of the most common type of bugs any programmer witnesses in their projects. Let’s see how Kotlin deals with it.

在本教程中,我们将研究Kotlin Null安全性。 NullPointerException是任何程序员在其项目中见证的最常见的错误类型之一。 让我们看看Kotlin如何处理它。

Kotlin Null安全 (Kotlin Null Safety)

Kotlin compiler by default doesn’t allow any types to have a value of null at compile-time.
For Kotlin, Nullability is a type. At a higher level, a Kotlin type fits in either of the two.

默认情况下,Kotlin编译器不允许任何类型在编译时具有null值。
对于Kotlin,可空性是一种类型 。 在较高的级别上,Kotlin类型适合两者之一。

  • Nullability Type可空性类型
  • Non-Nullability Type不可为空类型

可空性作为一种类型 (Nullability as a Type)

We can’t define the following syntax in Kotlin.

我们无法在Kotlin中定义以下语法。

var str: String = "JournalDev Kotlin Archives"
str= null //compilation errorvar a : String = null // compilation error.

To set a type as Nullable we need to append a ? to the type as shown below.

要将类型设置为Nullable,我们需要附加一个? 更改为如下所示的类型。

var a : String? = null
var newStr : String? = "Kotlin Null Safety"
newStr = null

Now whenever we access a Nullable Referernce, we need to handle the null cases carefully.
Note: Adding a ? changes the type of a variable from String to String?, Int to Int? and so on.
The most common way is using the if else statements as seen below.

现在,每当我们访问一个Nullable Referernce时,我们都需要谨慎处理null情况。
注意 :添加一个? 将变量的类型从String更改为String ?,将Int更改为Int? 等等。
最常见的方法是使用if else语句,如下所示。

if(a!=null)
{
print("The value of a is $a")
}
else{
print("Sorry a is null")
}

Now the above approach can lead to plenty of if else nested brackets. Kotlin does provide a simpler way to access nullable references using Safe Calls.

现在,以上方法可以导致大量的嵌套括号。 Kotlin确实提供了一种使用“安全调用”访问可空引用的更简单方法。

安全通话 (Safe Calls)

To call a function or a property over a variable, we typically do the following thing.

要在变量上调用函数或属性,通常需要执行以下操作。

var a : String = "Hello"
print(a.length)

This WON’T always work with Nullable References.

这不会始终与可空引用一起使用。

var a : String? = "Hi"
print(a.length) //prints 2a = null
print(a.length) // compilation error

The dot reference can’t be used when the Nullable reference holds a null value.
Hence, Kotlin provides us with a safe call operator to use over Nullable References as shown below.

当Nullable引用包含空值时,不能使用点引用。
因此,Kotlin为我们提供了一个安全的调用运算符,可以在可空引用上使用,如下所示。

a = "Hi"
print(a?.length) //prints 2a = null
print(a?.length) //prints null

The safe call ?. executes the relevant call only when the value is non-null.
Else it prints a null for you.

安全呼叫?. 仅当该值非空时才执行相关的调用。
否则,它将为您打印一个空值。

Safe calls are handy when you need to keep nullability checkers over multiple variables as shown below.

需要在多个变量上保留可空性检查器时,安全调用非常方便,如下所示。

var streetName : String? = address?.locality?.street?.addressLine1

There’s another way to call properties on a nullable reference.

还有另一种方法可以在可为空的引用上调用属性。

!! 操作员 (!! Operator)

Contrary to the safe calls, the !!, also known as the not-null assertion, converts the nullable reference into its non-nullable type irrespective of whether it’s a null or not. This should be used only when you’re certain that the value is NOT NULL. Else it’ll lead to an NPE exception.

与安全调用相反,!!也称为非空断言,它将可空引用转换为其不可空类型,而不管其是否为空。 仅当您确定该值不为NULL时,才应使用此选项。 否则会导致NPE异常。

a = null
println(a!!.length) // runtime error.a = "Hi"
print(a!!.length) //prints 2

安全铸造 (Safe Casting)

The ? operator can be used for preventing ClassCastException as well(another commonly seen exception).

? 运算符也可以用于防止ClassCastException (另一个常见的异常)。

var b : String ="2"
var x : Int? =  b as? Int
println(x) //prints null

In the above code, we’re safe cast the variable b using

在上面的代码中,我们可以安全地使用

as?

. If the cast isn’t successful, the value is set to null thereby preventing ClassCastException.
Another example:

。 如果转换不成功,则将该值设置为null,从而防止ClassCastException
另一个例子:

var array1 : Array<Any?> =  arrayOf("1","2","3")
var i : Int? = array1[0] as? Int
println(i) //prints null
var s : String? = array1[0] as? String
print(s) //prints 1

猫王算子 (Elvis Operator)

Up until now, whenever the safe call operator returns a null value, we don’t perform an action and print null instead. The Elvis operator ?: allows us to set a default value instead of the null as shown below.

到目前为止,只要安全调用运算符返回null值,我们就不会执行任何操作,而是打印null。 Elvis运算符?:允许我们设置默认值而不是null,如下所示。

var newString : String?  = "JournalDev.com"
println(newString?.length) //prints 14
newString = null
println(newString?.length?:"-1") //prints -1

The elvis operator is equivalent to the following:

elvis运算符等效于以下内容:

if(newString!null)
{
print(newString.length)
}
else{
print("-1")
}

Another sample:

另一个示例:

var streetName : String? = address?.locality?.street?.addressLine1 ?: "Street Name not found"

使用let() (Using let())

Let function executes the lamda function specified only when the reference is non-nullable as shown below.

Let函数仅在引用不可为空时才执行指定的lamda函数,如下所示。

newString = " Kotlin from Android"
newString?.let { println("The string value is: $it") }
newString = null
newString?.let { println("The string value is: $it") }

The statement inside let is a lamda expression. It’s only run when the value of newString is not null.
it contains the non-null value of newString

let中的语句是一个lamda表达式。 仅在newString的值不为null时运行。
it包含newString的非null值

使用Also() (Using also())

also behaves the same way as let except that it’s generally used to log the values. It can’t assign the value of it to another variable.
Here’s an example of let and also changed together.

also的行为方式相同的let ,只不过它通常用来记录的值。 它不能的值赋给it另一个变量。
这是let和一起更改的示例。

var c = "Hello"newString = " Kotlin from Android"
newString?.let { c = it }.also { println("Logging the value: $it") }

Note: The statement present inside let can’t be placed in also. Vice-versa can work though.

注意: let内部的语句不能also放置在。 反之亦然。

筛选出空值 (Filtering Out Null Values)

We can filter out Null Values from a collection type using the following function:

我们可以使用以下函数从集合类型中过滤出Null值:

var array2: Array<Any?> = arrayOf("1", "2", "3", null)
var newArray = array2.filterNotNull()
println(newArray.size) //prints 3

Java互操作性 (Java Interoperability)

Since Java doesn’t force you to state type as Nullable or Non-Nullable type, Kotlin compiler doesn’t give an error for the following:

由于Java不会强迫您将类型声明为Nullable或Non-Nullable类型,因此Kotlin编译器不会针对以下内容给出错误:

var javaObject = MyClass(null)

If you set the Java Annotation @Nullable or @NotNull, the Kotlin compiler would consider them as Nullable or Not Nullable References.
Remember : Nullable references require a ? in Kotlin.

如果您设置Java注释@Nullable或@NotNull,则Kotlin编译器会将其视为Nullable或Not Nullable引用。
记住:可空引用需要一个? 在Kotlin。

项目结构 (Project Structure)

The Kotlin Project below contains various sub-topics we’ve covered in Kotlin till now.

下面的Kotlin项目包含到目前为止我们在Kotlin中涵盖的各种子主题。

That’s all we’ve got in Kotlin Null Safety. You can download the IntelliJ project that contains the various code snippets we’ve covered in Kotlin so far. Play around with it!

这就是我们在Kotlin Null Safety中所拥有的全部。 您可以下载IntelliJ项目,其中包含我们到目前为止在Kotlin中介绍的各种代码段。 玩吧!

Download Kotlin Example Project下载Kotlin示例项目

References : Official Docs

参考资料: 官方文件

翻译自: https://www.journaldev.com/17568/kotlin-null-safety-nullable

kotlin null

kotlin null_Kotlin Null安全– Kotlin可空相关推荐

  1. 疯狂kotlin讲义连载之Kotlin的基础类型--null安全

    null安全可以说是Kotlin语言对Java的重大改进之一,这样可以避免Java编程时令人恐惧的"NullPointerException"(简称:NPE).但话说回来,null ...

  2. Kotlin实战指南六:可空类型、非可空类型

    转载请标明出处:https://blog.csdn.net/zhaoyanjun6/article/details/87877529 本文出自[赵彦军的博客] 可空类型.非可空类型 变量可空类型 方法 ...

  3. Kotlin学习笔记(2)- 空安全

    系列文章全部为本人的学习笔记,若有任何不妥之处,随时欢迎拍砖指正.如果你觉得我的文章对你有用,欢迎关注我,我们一起学习进步!kotlin学习笔记系列首发简书和CSDN Kotlin学习笔记(1)- 环 ...

  4. n-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView

    我这是把java转kotlin,报错提示: java.lang.IllegalArgumentException: Parameter specified as non-null is null: m ...

  5. Parameter specified as non-null is null method kotlin.jvm.internal.Intrinsics.checkNotNullParameter

    问题描述 Android 的 Java代码通过Android Studio自动化转换Kotlin报错 java.lang.NullPointerException: Parameter specifi ...

  6. 学习Kotlin(一)为什么使用Kotlin

    推荐阅读: 学习Kotlin(一)为什么使用Kotlin 学习Kotlin(二)基本语法 学习Kotlin(三)类和接口 学习Kotlin(四)对象与泛型 学习Kotlin(五)函数与Lambda表达 ...

  7. 第3章 Kotlin语言基础 《Kotlin 极简教程》

    2019独角兽企业重金招聘Python工程师标准>>> 第3章 Kotlin语言基础 掌握基础,持续练习 学习任何东西,都是一个由表及里的过程.学习一门编程语言也一样.对于一门编程语 ...

  8. Kotlin 开始篇之 Kotlin 的优点

    Kotlin 开始篇之 Kotlin 的优点 文章目录 Kotlin 开始篇之 Kotlin 的优点 前言 正文 Kotlin 的优点 1. 欢迎来到 kotlin 的糖果乐园 2. 人性化语法糖之一 ...

  9. kotlin 对话框_使用Kotlin的Android警报对话框

    kotlin 对话框 In this tutorial, we'll be discussing Alert Dialogs and implement them in our Android App ...

最新文章

  1. AudioStreamer电话打进时崩溃
  2. 械模拟计算器 - 计算尺
  3. Nicholas C. Zakas如何面试前端工程师
  4. CTFshow 爆破 web28
  5. new/delete和malloc/free的区别
  6. 【MCtalk直播】全面复盘直播答题,深度剖析产品架构的难点与坑
  7. 前端学习(3115):react-hello-初始化state
  8. python读取多个文件csv_Python:读取多个文本文件并写入相应的csv文件
  9. pygame的最小系统
  10. 《信号与系统学习笔记》—z变换(二)
  11. 简单易学Matlab深度学习教程--矩阵
  12. eclipse-登录注册web项目-练
  13. 如何将时间字体LED化(类似电子表)显示
  14. 我的世界学园都市java_我的世界学园都市地图整合包
  15. ExtJS控件主要功能用法
  16. centos 禁止自动锁屏
  17. 获取token的两种方法
  18. 新的樱桃键盘 好想要啊
  19. python:实现IIR 滤波器算法(附完整源码)
  20. VScode怎么开启本地服务器及本地调试?

热门文章

  1. EF 保证线程内唯一 上下文的创建
  2. Windows phone 8 学习笔记(1) 触控输入
  3. zoj 3261 Connections in Galaxy War
  4. 搜狗云输入法对外提供调用体验
  5. [转载] Python利用openpyxl模块读取excel文件内容
  6. 端口截听实现端口隐藏 嗅探与攻击
  7. EntityFramework6.X 之 Operation
  8. 软件工程实践_Task2_sudoku
  9. 算法总结之 在数组中找到一个局部最小的位置
  10. 从程序员到项目经理(24):慎于问敏于行 - 忠于工作不等于奴性