Search code examples
kotlinlambdainline

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


Solution

  • 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()
        }
    }