给定函数foo:
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
Run Code Online (Sandbox Code Playgroud)
我们可以做的:
foo("a message", { println("this is a message: $it") } )
//or
foo("a message") { println("this is a message: $it") }
Run Code Online (Sandbox Code Playgroud)
现在,假设我们有以下功能:
fun buz(m: String) {
println("another message: $m")
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以将"buz"作为参数传递给"foo"?就像是:
foo("a message", buz)
Run Code Online (Sandbox Code Playgroud)
Jay*_*ard 157
使用::以表示一个函数引用,然后:
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)
}
Run Code Online (Sandbox Code Playgroud)
从Kotlin 1.1开始,您现在可以通过在函数引用运算符前面添加实例来使用类成员函数(" 绑定可调用引用 "):
foo("hi", OtherClass()::buz)
foo("hi", thatOtherThing::buz)
foo("hi", this::buz)
Run Code Online (Sandbox Code Playgroud)
erl*_*man 11
只需在方法名称前使用“::”
fun foo(function: () -> (Unit)) {
function()
}
fun bar() {
println("Hello World")
}
Run Code Online (Sandbox Code Playgroud)
foo(::bar) 输出:Hello World
关于成员函数作为参数:
码:
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) })
}
Run Code Online (Sandbox Code Playgroud)
科特林 1.1
用于::参考方法。
喜欢
foo(::buz) // calling buz here
fun buz() {
println("i am called")
}
Run Code Online (Sandbox Code Playgroud)
如果你想传递setter和getter方法。
private fun setData(setValue: (Int) -> Unit, getValue: () -> (Int)) {
val oldValue = getValue()
val newValue = oldValue * 2
setValue(newValue)
}
Run Code Online (Sandbox Code Playgroud)
用法:
private var width: Int = 1
setData({ width = it }, { width })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47661 次 |
| 最近记录: |