android - Kotlin Null 安全警告 Unexpected tokens (use ; to separate expressions on the same line)

标签 android null kotlin warnings kotlin-null-safety

我正在尝试 Elvis operator在我的应用程序中使用 Kotlin 代码并收到以下警告:

Unexpected tokens (use ; to seperate expressions on the same line)

代码:

    var key: String = "KEY is"
    /* "check" is name of String variable which can be null
    Warning coming on following statement*/
    var str : String = check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

有什么解决办法吗?

最佳答案

我不明白为什么您在这里需要任何 null 安全运算符。您的所有变量都不可为空。


你写的

check?key.replace("KEY", "ABDS-ASDSA-DSSS")?:check

?(在 check 之后)不是 Kotlin 中的运算符。

您可能想要 ternary conditional operator, which is simply replaced by if/else .

从您的评论来看,您似乎想要 safe call不过,运算符是 ?.,而不是 ?

check?.key?.replace("KEY", "ABDS-ASDSA-DSSS") ?: check

Elvis operator 之间有区别和安全调用运算符(operator)。 Elvis 运算符使用表达式,而安全调用运算符只是空安全属性访问或方法调用

Elvis 运算符如果不为 null 则返回其第一个操作数,否则返回第二个操作数。

如果接收者为空,?. 运算符返回 null,否则返回调用结果。

关于android - Kotlin Null 安全警告 Unexpected tokens (use ; to separate expressions on the same line),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640028/

相关文章:

java - 0 使用图书馆项目时返回获取资源的 ID

python - cassandra 没有为后来在 python 模型中添加的新列设置默认值

php - PHP 中的 MySQL NULL

.net - 为什么我与 System.Data.DataRow 对象中包含的值的 null 比较失败?

kotlin - 改造为所有端点插入相同的查询参数

lazy-evaluation - 是否可以延迟初始化属性并断言它?

android - 如何检查一个方法是否没有被 mockk 调用?

android - CameraKitView 库未使用 Kotlin 进行初始化

java - 使用 ViewPager 在 Xamarin.Android 上以轮播样式显示图像幻灯片并使用突出的子项进行填充,Viewpager 错误地计算参数

Android ScriptIntrinsicBlur 不会模糊整个图像并生成透明边缘