gpt4 book ai didi

Kotlin null 安全性?

转载 作者:行者123 更新时间:2023-12-02 06:12:21 31 4
gpt4 key购买 nike

让我们有一个函数 foo 和一个类 Bar:

fun foo(key: String): String? {
// returns string or null
}

class Bar(x: String, y: String) {
// ...
}

现在,让我们看一下代码:

val x = foo("x")
val y = foo("y")
if (x.isNotEmpty() && y.isNotEmpty())
return Bar(x, y)

问题是这段代码无法编译。因为它需要 Bar(x!!, y!!)

但是,当我用其内容替换该函数时,就不需要 !! 了。

val x = foo("x")
val y = foo("y")
if ((x != null && x.length() > 0) && (y != null && y.length() > 0))
return Bar(x, y)

为什么无法从函数 .isNotEmpty() 解析 null 检查?

最佳答案

这在理论上是可能的,但这意味着要么1. isNotEmpty() 的声明必须向编译器传达以下事实:如果结果为 true,则 x 保证为非空2. 对任何函数体的更改都可能导致其调用点无法编译。

选项2是绝对不能接受的。选项 1 需要类型系统中有一个相当具有表现力的机制,我们决定目前不添加该机制,因为它可能会让用户的事情变得复杂。

我们计划通过内联函数支持类似的功能,但仍在考虑中。

关于Kotlin null 安全性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23779678/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com