在 Kotlin 中将接口作为参数传递 [英] Pass interface as parameter in Kotlin
本文介绍了在 Kotlin 中将接口作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想像这样传递一个接口作为参数:
I want to pass an interface as parameter like this:
class Test {
fun main() {
test({})
// how can I pass here?
}
fun test(handler: Handler) {
// do something
}
interface Handler {
fun onCompleted()
}
}
在 Java 中,我可以使用像 test(new Handler() { .......... })
这样的匿名函数,但在 Kotlin 中我不能这样做.有人知道怎么做吗?
In Java, I can use anonymous function like test(new Handler() { .......... })
, but I can't do this in Kotlin. Anyone know how to do this?
推荐答案
在 Kotlin 中你可以:
In Kotlin you can do :
test(object: Handler {
override fun onComplete() {
}
})
或者以同样的方式创建一个属性:
Or make a property the same way:
val handler = object: Handler {
override fun onComplete() {
}
}
而且,在代码中的某处:测试(处理程序)
And, somewhere in code: test(handler)
这篇关于在 Kotlin 中将接口作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文