Reputation: 2087
kotlin has two buildin extension functions in kotlin.text
:
public actual inline fun String.toBoolean()
public actual inline fun String?.toBoolean()
Now I want to add toBoolean
for Any?
:
fun Any?.toBoolean(): Boolean {
return when(this){
null -> false
is Boolean -> this
is Boolean? -> this
// Here toBoolean() is this function itself, not kotlin.text.String.toBoolean
else -> toString().toBoolean()
}
}
in else -> toString().toBoolean()
, the toBoolean()
function is not same-name extension function in kotlin.text, see the comment.
I tried to import kotlin.text.toBoolean or kotlin.text.String.toBoolean, but didn't work.
Upvotes: 0
Views: 196
Reputation: 93609
You can import the function you want to call using a different name like this:
import kotlin.text.toBoolean as stringToBoolean
fun Any?.toBoolean(): Boolean {
return when(this){
null -> false
is Boolean -> this
is Boolean? -> this
else -> toString().stringToBoolean()
}
}
By the way, is Boolean? -> this
is a redundant check.
Upvotes: 4