Kotlin避免对null进行明智的强制转换 [英] Kotlin avoid smart cast for null check
问题描述
因此,我正在尝试减少此代码,并避免来自IDE的智能转换提示.
我的想法是,我有一个nullable
类型的nullable
变量,我想将其映射到R
,或者我只是从供应商那里获得R
,以防该变量为null
.
So I'm trying to reduce this code and avoid the smart cast hint from IDE.
The idea is I have a nullable
variable of type T
and I want to either map it to R
or I just get R
from a supplier in case the variable is null
.
我尝试了不同的方法并提出了这个方法.仍然给了我聪明的演员提示.
I've tried different approaches and came up with this one. Still it gives me the smart cast hint.
fun <T, R> T?.func(mapper: (T) -> R, supplier: () -> R): R =
when(this) {
null -> supplier()
else -> mapper(this) // smart cast
}
但是我不喜欢将其中一个lambda括在括号中.例如.
But I don't like the need for wrapping one of the lambdas in parenthesis. For example.
fun foo(value: String?): Int =
value.func({ it.length + 20}) { 30 }
这似乎很奇怪,但我的观点是将变量不是nullable
传递给生成R
的函数,或者调用生成R
的函数.
This may seem odd but the ideia in my context was to pass the variable as not nullable
to a function that produced a R
or call a function that generated a R
.
fun bar(value: T?): R =
when(value) {
null -> func1()
else -> func2(value) // smart cast
}
注意:我已经阅读了此,但它并不相同.
Note: I've read this but its not the same.
推荐答案
以下应避免使用智能转换提示
Following should avoid the smart cast hint
fun <T, R> T?.func(mapper: (T) -> R, supplier: () -> R): R {
return this?.let { mapper(it) } ?: supplier()
}
这篇关于Kotlin避免对null进行明智的强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!