首页 文章

Kotlin - 具有多个参数的内联函数

提问于
浏览
0

我可以在Kotlin中定义一个内联函数:

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

但是我怎么称呼这个功能呢?

对于只有一个参数的普通内联函数,我会使用:

func {
    doSomething()
}

具有多个内联参数的函数是否有类似的语法?

2 回答

  • 1

    有几种方法可以实现这一目标 . 可能最好的方法是在最后一个参数之前使用bound function reference

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

    如果要调用对象方法,只需将对象名称放在 :: 前面

    class Bar {
        val baz = Baz()
    
        fun foo() {
            func(baz::func2, ::foo)
        }
    
        fun func(a: () -> Unit, b: () -> Unit) {
            a()
            b()
        }
    }
    
    class Baz{
        fun func2(){}
    }
    
  • 1

    只有最后一个函数参数在调用运算符外传递 . 例如:

    fun foo(a: () -> Unit, b: () -> Unit)
    
    foo({ println("hello") }) {
        println("world")
    }
    

    其他函数参数只是在括号内的正常参数列表中传递,最后一个可以选择性地移动到这些括号之外,就像大多数调用一样 .

相关问题