Kotlin智能铸件无法使用扩展功能



我正在尝试用扩展函数检查可为null的对象,但在调用此函数后智能强制转换不起作用。

fun <T> T?.test(): T = this ?: throw Exception()
val x: String? = "x"
x.test()
x.length // Only safe (?.) or non-null asserted (!!) calls are allowed on a nullable receiver of type String?

是Kotlin虫吗?如果没有,为什么没有隐式选角?

正如@Madhu Bhat在上面的评论中提到的,您的变量'x'仍然可以为null。你可以这样简单地使用你的功能:

x.test().length

否则,您可以通过以下内联函数检查null,然后直接对变量执行任何函数。(注意"合同"和注释"@ExperimentalContracts"的用法(

@ExperimentalContracts
fun <T> T?.notNull(): Boolean {
contract {
returns(true) implies (this@notNull != null)
}
return this != null
}

现在你可以像这个一样使用这个功能

if(x.notNull()){
x.length
}

但是,如果您使用此函数只是为了检查可空性,那么它似乎就没有那么有用了。

点击此处了解更多关于Kotlin合同的信息

最新更新