t.v is not resolved
# announcements
i
t.v is not resolved
s
Because
poly
returns a value of type
E
and the
sealed class E
itself does not define the property
v
.
i
I don’t like to use Any? as result type, is there a way I can get the value from poly’s result?
p
Put your code inside triple backticks, please.
n
you can use the same code as in
poly2
s
@Ifvwm I noticed the name of your Kotlin source file. If you try to create an left-right or error-value type like
Either
or
Result
, this may work for you.
Copy code
sealed class Result<out E, out T> {
    data class Success<out T>(val value: T) : Result<Nothing, T>()
    data class Failure<out E>(val error: E) : Result<E, Nothing>()
}

fun <E, T, T2> Result<E, T>.map(function: (T) -> (T2)): Result<E, T2> = when (this) {
    is Result.Success -> Result.Success(function(value))
    is Result.Failure -> this
}

fun <E, E2, T> Result<E, T>.mapError(function: (E) -> (E2)): Result<E2, T> = when (this) {
    is Result.Success -> this
    is Result.Failure -> Result.Failure(function(error))
}

fun <E, T, R> Result<E, T>.extract(whenFailure: (E) -> R, whenSuccess: (T) -> R): R = when (this) {
    is Result.Success -> whenSuccess(value)
    is Result.Failure -> whenFailure(error)
}
where
E
is the error-type and
T
is the value type. You can create additional extension functions for your own particular use-cases.
i
@streetsofboston I have a little confused about your code, 1. I saw you wrote Result<out E, out T> then you use Result<E,T>, does this E is out E? and Nothing is out E in Result<Nothing, T>? 2. you use fun keyword, but I don’t find the function name
s
1) Yes. Take a look, on the official website of Kotlin, at how generics work in Kotlin and how Kotlin does this at the declaration of a type. 2) The function names are there: map, mapError and extract.