英文:
Pass a static method as a parameter to another method in Kotlin
问题
根据这个问题,可以将一个函数作为参数传递给另一个函数,如下所示
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
fun buz(m: String) {
println("another message: $m")
}
fun something() {
foo("hi", ::buz)
}
同样,我们也可以传递来自类的方法
class OtherClass {
fun buz(m: String) {
println("another message: $m")
}
}
foo("hi", OtherClass()::buz)
但是,如果我们要传递的方法是静态的(在伴生对象内部)呢?
class OtherClass {
companion object {
fun buz(m: String) {
println("another message: $m")
}
}
}
我知道由于它是静态的,我们可以直接调用该方法,而不必将其作为参数传递,但是仍然存在一些情况(例如在利用现有代码时),这将会很有用。
英文:
As per this question, a function can be passed as a parameter to another function as shown below
fun foo(m: String, bar: (m: String) -> Unit) {
bar(m)
}
fun buz(m: String) {
println("another message: $m")
}
fun something() {
foo("hi", ::buz)
}
Similarly, we can also pass a method from a class
class OtherClass {
fun buz(m: String) {
println("another message: $m")
}
}
foo("hi", OtherClass()::buz)
But what if the method we want to pass is static (within a companion object)?
class OtherClass {
companion object {
fun buz(m: String) {
println("another message: $m")
}
}
}
I am aware that since it is static we can simply call the method directly without having to resort to passing it as a parameter, however, there are still some situations (such as when taking advantage of pre-existing code) where this would be useful.
答案1
得分: 3
访问类的伴生对象使用 ${className}.Companion
。所以...
foo("hit", OtherClass.Companion::buz)
。
英文:
To access companion object of class use ${className}.Companion
. So...
foo("hit", OtherClass.Companion::buz)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论