Any idea how can I do a `getOrElse` on my `ResultW...
# announcements
j
Any idea how can I do a
getOrElse
on my
ResultWrapper
class?
Copy code
sealed class ResultWrapper<out T> {
    data class Success<out T : Any>(val value: T) : ResultWrapper<T>()
    data class Failure<out T : Any>(val failure: Throwable) : ResultWrapper<T>()

    inline fun <B> fold(ifFailure: (Throwable) -> B, ifSuccess: (T) -> B): B =
        when (this) {
            is Failure -> ifFailure(failure)
            is Success -> ifSuccess(value)
        }

    companion object {
        fun <T : Any> just(t: T): ResultWrapper<T> = Success(t)
        fun <T : Any> raise(t: Throwable): ResultWrapper<Throwable> = Failure(t)
    }
}
I'm getting a
Success(value=MyModel(....))
And I need to do an
Assert.assertEquals(expectedResult, result)
where
expectedResult
is
MyModel
and
Result
is
Success(value=MyModel(....))
. Any idea?
d
val valueOrDefault = result.fold({ defaultValue }, { it })
Or you can write a helper function:
Copy code
inline fun <T> ResultWrapper<T>.getOrDefault(defaultValue: (err: Throwable) -> T): T {
  return fold(defaultValue, {it})
}
j
The thing is that I can not call this
getOrDefault
Looks like it's not visible... I can do a fold tho
d
Not sure what you mean.
You have to implement this function first.
j
which function?
d
The one I showed above
j
Yes, I did it, the thing is that I can do `result.fold()`but no
result.getOrDefault
I do not know why
d
Can you show your code?
w
Curious, why can’t use the
Result
from Kotlin?!
👆 1
Or look in how they tackle these methods in
Result
extensions?!
s
Would this work:
Assert.assertEquals(ResultWrapper.just(expectedResult), result)
?
j
@streetsofboston sure it would work, but the idea is having the model itself, it looks to me like a hacky way
That's why I wanted a
getOrNull
or
getOrDefault
method to get the model inself
s
I don’t think it is hacky… You get a result, which is a
ResultWrapper
, which you assert with the expected value that also should be a `ResultWrapper`…
j
Yes, that was not my intention, I meant it's an option and it works, but I'm looking for a
getOrDefault
solution, thank you though
w
Maybe it is easier for you to write your own
assert
?! As I suspect is for your tests?!
Copy code
@Test
    fun asas() {
        val expectedResult = "asas"
        val result: ResultWrapper<String> = ResultWrapper.just("asas")
        assertEquals(expectedResult, result)
    }

    private inline fun <reified T : Any> assertEquals(expectedResult: T, result: ResultWrapper<T>) {
        when (result) {
            is ResultWrapper.Success<*> -> org.junit.Assert.assertEquals(expectedResult, result.value)
            is ResultWrapper.Failure<*> -> org.junit.Assert.assertEquals(expectedResult, result.failure)
        }
    }