chriptus13
chriptus13

Reputation: 717

Kotlin avoid smart cast for null check

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
    }

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 }

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.

Upvotes: 0

Views: 500

Answers (1)

sidgate
sidgate

Reputation: 15254

Following should avoid the smart cast hint

fun <T, R> T?.func(mapper: (T) -> R, supplier: () -> R): R {
    return this?.let { mapper(it) } ?: supplier()
}

Upvotes: 1

Related Questions