Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callback to constructor with multiple parameters

What I've tried so far is callback with single parameter and it works:

class SomeClass (something:Int = 3, val callback: (Int) -> Unit) {
    fun doSomething() {
      callback(11)
    }
}

class AnotherClass {

    val something = SomeClass({onSomething(it)}) 

    protected fun onSomething(num: Int) {
        // ...
    }
}

But how to implemented it with multiple parameters like:

class SomeClass (something:Int = 3, val callback: (Int, String) -> Unit) {
    fun doSomething() {
      callback(11, "Yeah")
    }
}

class AnotherClass {

    val something = SomeClass(/* ...... what goes here???? */) 

    protected fun onSomething(num: Int, str: String) {
        // ...
    }
}
like image 874
Jocky Doe Avatar asked Sep 01 '25 22:09

Jocky Doe


1 Answers

Just use the lambda expression syntax with explicit parameters:

val something = SomeClass { num, str -> onSomething(num, str) }

When passing a lambda as the last parameter, you can omit the parenthesis.

Also, you can use a bound function reference when the expected and actual function signatures match exactly:

val something = SomeClass(this::onSomething)
like image 123
hotkey Avatar answered Sep 04 '25 03:09

hotkey