Gabi Moreno
Gabi Moreno

Reputation: 881

Simplify Kotlin function with a lambda

I have this function on FooClass class:

fun foo(id: Int, listener: Listener<JsonElement>) {
    enqueue(listener, apiService.getFoo(id))
}

This is the interface:

interface Listener<T> {
    fun onSuccess(result: T?)

    fun onFailure()
}

When I call it, I do this:

FooClass().foo(id, object : FooClass.Listener<JsonElement> {
    override fun onSuccess(result: JsonElement?) {}
    override fun onFailure() {}
})

I want to make a lambda to simplify when I make the call. Something like this:

fun foo {id ->
    // Perform onSuccess
    // Perform onFailure
}

I know this is basic, but I'm a mess... :-(

Thank you so much for the help.

Upvotes: 3

Views: 333

Answers (2)

Gabi Moreno
Gabi Moreno

Reputation: 881

Thanks to @EpicPandaForce I have found a solution. It is this:

fun foo(id: Int, success: (JsonElement?) -> Unit, error: () -> Unit) {
    enqueue(apiService.getFoo(id), object : Listener<JsonElement> {
        override fun onSuccess(result: JsonElement?) = success(result)

        override fun onFailure() = error()
    })
}

I have refactored the order of the parameters on the enqueue function to be more readable.

To call the function is as simple as this:

    FooClass().foo(id,
            success = { result ->
                // Handle success result
            },
            error = {
                // Handle error
            }
    )

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

You'll need to use some tricks for that.

typealias SuccessCallback<T> = (T?) -> Unit
typealias FailureCallback = () -> Unit

inline fun FooClass.foo(id: Int, crossinline success: SuccessCallback<JsonElement?>, crossinline failure: FailureCallback) {
    foo(id, object: FooClass.Listener<JsonElement> {
        override fun onSuccess(result: JsonElement?) = success(result)
        override fun onFailure() = failure()
    })
}

Now you should be able to call

FooClass().foo(id, 
    success = { result: JsonElement? -> 
        ... 
    }, 
    failure = { 
    }
)

Upvotes: 6

Related Questions