Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Kotlin inline function params is must not be null

enter image description here

inline fun <T, R> isNullObject(value: T?, notNullBlock: (T) -> R, isNullBlock: (() -> Unit)? = null) {

if (value != null) {
    notNullBlock(value)
} else {
    if(isNullBlock != null){
        isNullBlock()
    }
}

}

I tried to write some higher-order functions to facilitate development, but it is error

like image 646
Sean Eli Avatar asked Dec 31 '22 22:12

Sean Eli


1 Answers

I think it is related to how inline functions and lambdas passed to it are inlined. The inline modifier affects both the function itself and the lambdas passed to it: all of those will be inlined into the call site. It seems Kotlin doesn't allow to use nullable lambdas.

If you want some default value for isNullBlock parameter you can use empty braces isNullBlock: () -> Unit = {}:

inline fun <T, R> isNullObject(value: T?, notNullBlock: (T) -> R, isNullBlock: () -> Unit = {}) {

    if (value != null) {
        notNullBlock(value)
    } else {
        isNullBlock()
    }
}
like image 138
Sergey Avatar answered Jan 03 '23 04:01

Sergey