kotlin: Invoking methods

Can invoke a kotlin method reference, or a class method reference if you pass the object instance to use.

fun main() {
    val f = Foo(123)

    f.bar("Call method")

    (f::bar)("Call method ref")
    f::bar.invoke("Invoke method ref")

    val mr = f::bar
    mr("Call method ref variable")
    mr.invoke("Invoke method ref variable")

    (Foo::bar)(f, "Call class method ref")
    Foo::bar.invoke(f, "Invoke class method ref")

    val cr = Foo::bar
    cr(f, "Call class method ref variable")
    cr.invoke(f, "Invoke class method ref variable")
}

data class Foo(val v: Int) {
    fun bar(s: String) {
        println(v.toString() + " " + s)
    }
}
Published on: 23 Dec 2022