Reputation: 3192
I am trying check nullable object with extension function, but smart casting not work after calling this function.
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?
Is it a Kotlin bug? If not, why there is no implicit casting?
Upvotes: 3
Views: 1646
Reputation: 1282
As @Madhu Bhat mentioned in comment above, your variable 'x' is still nullable. You may use your function simply like this:
x.test().length
Otherwise you can check for null by following inline function and then perform any functions directly on the variable. (Note the usage of 'contract' and annotations '@ExperimentalContracts')
@ExperimentalContracts
fun <T> T?.notNull(): Boolean {
contract {
returns(true) implies (this@notNull != null)
}
return this != null
}
Now you can use this function like this
if(x.notNull()){
x.length
}
But its not seems so useful if your using this function just to check nullability.
Check here to know more about Kotlin contracts
Upvotes: 3