Hi folks, I'm trying to create a data type aking t...
# announcements
i
Hi folks, I'm trying to create a data type aking to
Result<T>
but which 1) Can return an arbitrary type as error and 2) Doesn't have a success payload. Here's the solution I came up with. I wonder if it can be expressed more elegantly?
Copy code
sealed class EmptyResult<E> {
    class Success<E> : EmptyResult<E>()
    data class Failure<E>(val error: E): EmptyResult<E>()
}

fun foo(): EmptyResult<String> = EmptyResult.Success()
d
I would make
Success
a singleton:
Copy code
sealed class EmptyResult<out E> {
    object Success : EmptyResult<Nothing>()
    data class Failure<out E>(val error: E): EmptyResult<E>()
}
fun foo(): EmptyResult<String> = EmptyResult.Success
h
You can use Arrow’s Either
s
@diesieben07 already provided the one optimisation I had in mind, but here’s a nice article about the topic in general https://phauer.com/2019/sealed-classes-exceptions-kotlin/
i
@diesieben07 Thanks! I tried first to use
object
but had an issues with generics. In your code it's fixed 🙂
@Hugh Bollen don't want to use a third party for this, but thanks, arrow is on my radar...
@Stephan Schroeder thanks for the article, though I'm already aware of this 🙂
👍 1