is there a way to conditionally invoke a nullable ...
# announcements
b
is there a way to conditionally invoke a nullable receiver function?
i.e.
Copy code
class Foo(
    private val receiver: (Number.() -> Number)? = null
) {
    fun doSomething(num: Number): Number {
        // Call num.receiver() here if receiver is non-null
    }
}
unfortunately due to https://youtrack.jetbrains.com/issue/KT-4113 null-checking receiver won't smart cast it
for now i'm doing:
Copy code
class Foo(
    private val receiver: (Number.() -> Number)? = null
) {
    fun doSomething(num: Number): Number {
        return receiver?.let { <http://num.it|num.it>() } ?: num
    }
}
but wondering if there is a cleaner way
s
Copy code
return receiver?.invoke(num) ?: num
Copy code
class Foo(private val receiver: (Number.() -> Number)) {
    fun doSomething(num: Number): Number {
        return receiver?.invoke(num) ?: num
    }
}
fun main(argv: Array<String>) {

    val f = Foo({ this.toInt() * 2 })

    println(f.doSomething(3))

}
b
ah...thanks! intellij suggested the invoke, but i couldn't figure out what it was referring to (what way to call it)
s
you can also use if and smart casting, a bit more long winded but
Copy code
return if(receiver != null) {
            receiver(num)
        } else {
            num
        }
b
i tried that, but there's a bug unfortunately (linked above)