将一个静态方法作为参数传递给 Kotlin 中的另一个方法

huangapple go评论68阅读模式
英文:

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).

huangapple
  • 本文由 发表于 2020年1月3日 20:26:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定