Home > database >  What is the meaning of following function parameter signature onChanged: ((Int?) -> Unit)? = null
What is the meaning of following function parameter signature onChanged: ((Int?) -> Unit)? = null

Time:06-20

I have a function with several parameters. One of these paramters is

private fun mySpecialFunction(
    variable1: Int,
    onChanged: ((Int?) -> Unit)? = null
)

Later in the function it is invoked like:

onChanged?.invoke(2)

And on the upper calling site, it is called like:

mySpecialFunction(
    variable1 = 1, 
    onChanged = {
        // do something with the number invoked above
    }
)

How is this usage of onChange called in Kotlin?

CodePudding user response:

onChanged is a nullable higher-order function. The ? in "((Int?) -> Unit)?" means that the value of onChanged can be null. Also, it has been assigned the default value null which means that if you don't pass a value for this parameter, it will be null.

The usual syntax for a higher order function is (Args) -> ReturnType. In your case, onChanged takes an nullable Int (Int?) as an argument and does not return anything i.e. returns Unit.

onChanged?.invoke(2) means that if onChanged is not null, invoke it and pass 2 as the argument.

mySpecialFunction(
    variable1 = 1, 
    onChanged = {
        // This section will get executed when the onChanged function is invoked. Here the passed `Int?` will be available as `it`
    }
)

CodePudding user response:

private fun mySpecialFunction(
    variable1: Int,
    // define nullable higher-order function with default parameter `null`
    onChanged: ((Int?) -> Unit)? = null
)

// nullsafe call && lamda invoke
onChanged?.invoke(2)

mySpecialFunction(
    variable1 = 1, 
    // define onChange lambda
    onChanged = {
    }
)

// equal to this
interface ChangeCallback {
    fun onChange(int: Int?)
}

fun mySpecialFunction(
    variable1: Int,
    onChange: ChangeCallback? = null
)

  • Related