UrK
UrK

Reputation: 2300

Kotlin Result type with generics and Void/Nothing return type

I am trying to use Kotlin's [Result][1] type. Though in case of success it does not return any value. I cannot get it to work for returning the value. The following line gives me trouble: complete(Result.success()). It doest not compile. I tried with both Result<Void> and Result<Nothing> but cannot make it work.

Any suggestions about how to make it work?

package me.test.app

import android.util.Log

class Test {

    fun foo(complete: (Result<Nothing>) -> Unit) {
        if (Math.random() > 0.5) {
            complete(Result.success())
        } else {
            complete(Result.failure(Throwable("too low")))
        }
    }

    fun bar() {
        foo { result ->
            result.fold({
                Log.i("APP", "Success")
            })
            {
                Log.i("APP", "Failure")
            }
        }
    }
}

Upvotes: 8

Views: 5406

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8432

You have to use Result<Unit>. Then you can call complete like this:

complete(Result.success(Unit))

Upvotes: 17

Related Questions