Kotlin:如何将一个函数作为参数传递给另一个?
给定函数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)
使用::
来表示函数引用,然后:
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) }
由于Kotlin 1.1现在可以使用作为类成员的函数(“ Bound Callable References ”),通过在函数引用操作符前添加实例:
foo("hi", OtherClass()::buz) foo("hi", thatOtherThing::buz) foo("hi", this::buz)
关于成员函数作为参数:
- Kotlin类不支持静态成员函数,所以不能调用成员函数,如: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) }) }
只要在方法名前使用“::”作为参数
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-- } }
Kotlin 1.1
这:: buz(如果在相同的类)或类():: BUZ如果不同
Kotlin目前不支持一流的功能。 关于这是否是一个很好的功能补充一直存在争议。 我个人认为他们应该。