Akihiro Yoshikawa
Akihiro Yoshikawa

Reputation: 127

simpler way to convert a function to a lambda in Kotlin?

Here, Handler is a function type. And doSomething is one of such a handler function. addHandler register it and give it a name. Question is are there simpler way to convert a function doSomething to a lambda?

typealias Handler = (cmd: String, obj: Any?) -> Any?

fun doSomething(cmd: String, obj: Any?): Any? {...}

fun addHandler(name: String, handler: Handler) {...}

fun foo() {
    addHandler("doSomething", { cmd, obj -> doSomething(cmd, obj) })
    // or in other syntax
    addHandler("doSomething") { cmd, obj -> doSomething(cmd, obj) }
}

Here, the phrase

{ cmd, obj -> doSomething(cmd, obj) }

is just converting a function to a lambda which has the same parameter sequence. C++ has very simple syntax &doSomething for it. How about in Kotlin?

Upvotes: 0

Views: 219

Answers (1)

zsmb13
zsmb13

Reputation: 89578

Kotlin also supports method references, in your case, you can do this:

addHandler("doSomething", ::doSomething)

Upvotes: 4

Related Questions