Use typealiases to make something more significant than Left, Right, .a and .b
Created
February 18, 2021 17:44
-
-
Save PascalLeMerrer/720b996372e3d48d7bcab10714333370 to your computer and use it in GitHub Desktop.
Using Arrow.Either in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias Result<A> = Either<Exception,A> | |
typealias Err = Either.Left<Exception> | |
typealias Ok<A> = Either.Right<A> | |
fun <T> Result<T>.value(): T? { | |
when (this) { | |
is Ok -> return this.b | |
is Err -> return null | |
} | |
} | |
fun <T> Result<T>.error(): Exception? { | |
when (this) { | |
is Err -> return this.a | |
is Ok -> return null | |
} | |
} | |
// Temp code to test Either | |
val result1: Result<Int> = Err(InternalErrorException("Something went wrong")) | |
when (result1) { | |
is Err -> println("result1.a ${result1.a}") | |
is Ok -> println("result1.b ${result1.b}") | |
} | |
val a = result1.exists { it < 4 } | |
val b = result1.exists { it > 4 } | |
println("result 1 < 4 $a") | |
println("result 1 > 4 $b") | |
result1.map { println("result1 map $it")} | |
result1.mapLeft { println("result1 mapLeft $it")} | |
println("result1.value ${result1.value()}") | |
println("result1.error ${result1.error()}") | |
val result2: Result<Int> = Ok(5) | |
when (result2) { | |
is Err -> println("result2.a ${result2.a}") | |
is Ok-> println("result2.b ${result2.b}") | |
} | |
println("result 2 < 4 ${result2.exists { it < 4 }}") | |
println("result 2 > 4 ${result2.exists { it > 4 }}") | |
result2.map { println("result2 map $it")} | |
result2.mapLeft { println("result2 mapLeft $it")} | |
println("result2.value ${result2.value()}") | |
println("result2.error ${result2.error()}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment