First of all, I want to clarify that my questions is for a personal code-style preference.
Let's say I have a method which takes an interface as parameter, and the said interface has two methods in it.
In kotlin, implementing the interface anonymously, we would have something like
client.execute(object : Callback() {
override fun onResponse(response: Response) {/*...*/}
override fun onError(error: Error) {/*...*/}
})
What I would like to do is to create an extensions for the client
object that would take two different interfaces such as
interface ClientResponse{fun onResponse(response: Response)}
interface ClientError{fun onError(error: Error)}
and then the new execute
method would look like
client.executeCustom(
{response -> /*...*/},
{error -> /*...*/}
})
so kind of a SAM solution.
Is it possible in any way?
This should be a fairly trivial extension to write, you can just take two lambda parameters immediately, and then create a Callback
instance inside that delegates calls to those lambdas:
fun Client.executeCustom(onResponse: (Response) -> Unit, onError: (Error) -> Unit) {
execute(object : Callback() {
override fun onResponse(response: Response) = onResponse(response)
override fun onError(error: Error) = onError(error)
})
}
This way, you don't even need to introduce new interfaces.