0

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?

1 Answer 1

4

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

addHandler("doSomething", ::doSomething)
Sign up to request clarification or add additional context in comments.

1 Comment

surprised. very nice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.