https://kotlinlang.org logo
#announcements
Title
# announcements
i

Ifvwm

06/22/2019, 3:32 AM
t.v is not resolved
s

streetsofboston

06/22/2019, 3:48 AM
Because
poly
returns a value of type
E
and the
sealed class E
itself does not define the property
v
.
i

Ifvwm

06/22/2019, 6:18 AM
I don’t like to use Any? as result type, is there a way I can get the value from poly’s result?
p

Pavlo Liapota

06/22/2019, 6:36 AM
Put your code inside triple backticks, please.
n

Nikky

06/22/2019, 10:02 AM
you can use the same code as in
poly2
s

streetsofboston

06/22/2019, 12:51 PM
@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

Ifvwm

06/23/2019, 2:58 AM
@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

streetsofboston

06/23/2019, 1:16 PM
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.
3 Views