2

Given that there are no checked exceptions in Kotlin, are Result types the correct way to indicate an exception occurred to the caller?

For example, I have the following function in my code:

suspend fun addUserToSignInHistory(user: User): Result<Unit> {
    return try {
        preferencesStore.edit { preferences ->
            users.add(user.id)
            preferences[USERS_KEY] = users
        }

        Result.success(Unit)
    } catch (t: Throwable) {
        Result.failure(t)
    }
}

Given that edit may throw an IOException or an Exception as per the documentation, is this the ideal way of handling this?

1
  • 4
    The code you have written is redundant since runCatching does the same thing with fewer lines - however I suspect the choice of return type and whether you catch or simply let the exception be handled at a higher level, will be situations so I doubt there is a 'correct' or 'ideal' solution.
    – DavidT
    Commented Jan 15 at 14:05

1 Answer 1

2

I think this is almost the ideal way of dealing with exceptions in Kotlin. Dealing with the Result objects is used very often in Kotlin because it makes it easier to make business logic decisions. On a functional level everything is right about your code. However you can still improve it and so a potentially better approach would be to do this instead, which is very similar, only that we do not explicitly create the Result objects and we let Kotlin do that for us:

suspend fun addUserToSignInHistory(user: User) = runCatching {
    preferencesStore.edit { preferences ->
        users.add(user.id)
        preferences[USERS_KEY] = users
    }
}

But indeed runCatching and namely the usage of Result is a standard when and if we want to programmatically deal with exceptions.

1
  • 1
    Yes, I modified my code after seeing @DavidT's comment. Thank you.
    – Adam
    Commented Jan 18 at 12:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.