2

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.

Community
  • 1
  • 1

1 Answers1

3

To access companion object of class use ${className}.Companion. So...

foo("hit", OtherClass.Companion::buz).

Cililing
  • 4,303
  • 1
  • 17
  • 35