0

I can define an inline function in Kotlin with:

inline fun func(a: () -> Unit, b: () -> Unit){
    a()
    b()
}

But how do I call this function?

For a normal inline function with only one parameter, I would use:

func {
    doSomething()
}

Is there a similar syntax for functions with more than one inline parameter?

2
  • You just put the first (at least) lambda inside parentheses, just like any other argument. Commented Dec 8, 2018 at 20:15
  • 1
    The way you call the function doesn't depend on whether it's inline. Commented Dec 8, 2018 at 22:46

2 Answers 2

3

Only the last function parameter is passed outside the call operator. For example:

fun foo(a: () -> Unit, b: () -> Unit)

foo({ println("hello") }) {
    println("world")
}

The other function parameters are just passed in the normal argument list inside the parenthesis, the last can optionally be moved outside of those parenthesis as is done with most calls.

Sign up to request clarification or add additional context in comments.

Comments

2

There are several ways to achieve this. Probably the nicest is to use a bound function reference for the parameters before the last one:

fun foo(){
    func(::foo){foo()}
    //this also works:
    func(::foo, ::foo)
    //or place the other call within parentheses in a lambda. (you can only put the last lambda behind the method call.
    func( { foo() } ){foo()}
}

inline fun func(a: () -> Unit, b: () -> Unit){
    a()
    b()
}

If you want to call an objects method just place that objects name in front of the ::

class Bar {
    val baz = Baz()

    fun foo() {
        func(baz::func2, ::foo)
    }

    fun func(a: () -> Unit, b: () -> Unit) {
        a()
        b()
    }
}

class Baz{
    fun func2(){}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.