gpt4 book ai didi

java - 为什么我在 Kotlin 中会收到错误 "Smart cast to ' Long' is possible"?但在 java 中却可以?

转载 作者:行者123 更新时间:2023-12-01 07:47:47 27 4
gpt4 key购买 nike

我尝试运行以下代码,但代码无法通过编译,出现错误:

Smart cast to 'Long' is impossible, because 'i' is a mutable property that could have been changed by this time

为什么?

class MyClass1(var i: Long?) {

fun change(): Long? {
if (i != null) {
return i + 10L
} else {
return 5L
}
}
}

我用Java编写了代码MyClass2,它可以很好地运行,为什么?

class MyClass2{
private Long i;

public MyClass2(Long k){
i=k;
}

public Long change(){
if (i!=null){
return i+10L;
}else {
return 5L;
}
}
}

最佳答案

因为 i 是一个 var,理论上它可以被空检查和加操作之间的另一个线程更改。

可以使用let函数来解决。它将通过将 i 的值作为参数提供给 let 来“捕获”它。

fun change(): Long? {
return i?.let { it + 10L } ?: 5L
}

关于java - 为什么我在 Kotlin 中会收到错误 "Smart cast to ' Long' is possible"?但在 java 中却可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47386583/

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