首页 文章

Kotlin:如何将函数作为参数传递给另一个?

提问于
浏览
64

给定函数foo:

fun foo(m: String, bar: (m: String) -> Unit) {
    bar(m)
}

我们可以做的:

foo("a message", { println("this is a message: $it") } )
//or 
foo("a message")  { println("this is a message: $it") }

现在,假设我们有以下功能:

fun buz(m: String) {
   println("another message: $m")
}

有没有办法可以将“buz”作为参数传递给“foo”?就像是:

foo("a message", buz)

6 回答

  • -1

    使用 :: 表示函数引用,然后:

    fun foo(m: String, bar: (m: String) -> Unit) {
        bar(m)
    }
    
    // my function to pass into the other
    fun buz(m: String) {
        println("another message: $m")
    }
    
    // someone passing buz into foo
    fun something() {
        foo("hi", ::buz)
    }
    

    Since Kotlin 1.1您现在可以使用类成员函数(“绑定可调用引用”),方法是在函数引用运算符前面添加实例:

    foo("hi", OtherClass()::buz)
    
    foo("hi", thatOtherThing::buz)
    
    foo("hi", this::buz)
    
  • -3

    关于成员函数作为参数:

    • Kotlin类没有't support static member function, so the member function can'被调用如:Operator :: add(5,4)

    • 因此,成员函数不能与First-class函数一样使用 .

    • 一个有用的方法是用lambda包装函数 . 它不优雅,但至少它是有效的 .

    码:

    class Operator {
        fun add(a: Int, b: Int) = a + b
        fun inc(a: Int) = a + 1
    }
    
    fun calc(a: Int, b: Int, opr: (Int, Int) -> Int) = opr(a, b)
    fun calc(a: Int, opr: (Int) -> Int) = opr(a)
    
    fun main(args: Array<String>) {
        calc(1, 2, { a, b -> Operator().add(a, b) })
        calc(1, { Operator().inc(it) })
    }
    
  • 1
  • 96

    Just use "::" in front of method name as parameter

    fun main(args: Array<String>) {
        runAFunc(::runLines)
    }
    
    
    fun runAFunc(predicate: (Int) -> (Unit)) {
       val a = "five"
       if (a == "five") predicate.invoke(5) else predicate.invoke(3)
    
    }
    
    fun runLines(numbers: Int) {
        var i = numbers
        while (i > 0) {
            println("printed number is $i")
            i--
        }
    }
    
  • 3

    科特林1.1

    this :: buz(如果在同一个类中)或Class():: buz如果不同

  • 5

    Kotlin目前不支持一流的功能 . 关于这是否是一个很好的补充功能一直存在争议 . 我个人认为应该这样做 .

相关问题