kotlin null_Kotlin Null安全– Kotlin可空

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 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 error

var 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 2

a = 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 2

a = 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 intellij tutorials

下面的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中介绍的各种代码段。 玩吧!

References : Official Docs

参考资料: 官方文件

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

kotlin null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值