Search code examples
kotlinarrow-kt

Extract value out of Kotlin arrow Either type and assign it to const


It would be a basic question, but I couldn't figure out a solution. I need to initialize a constant out of the right-side value of below either type.

val test: Either<String, Int> = 1.right()

I tried something like below but it shrinks the scope of the constant.

when(test) {
        is Either.Right -> {val get:Int = test.b}
        is Either.Left -> println(test.a)
    }

I want that get to be scoped outside of when statement. Is there any way to do it or Arrow Either is not made for this purpose?


Solution

  • The important question is: what should happen if the Either is Left. In this example it is created close to where it's used, so it is obvious to you as a developer. But to the compiler what is inside the Either can be either an Int or a String.

    You can extract the value using for example fold:

    val x = test.fold({ 0 }, {it}) // provide 0 as default in case the Either was a `Left`
    // x = 1
    

    another option is getOrElse

    val test = 1.right()
    val x = test.getOrElse { 42 } // again, default in case it was a `Left`
    // x = 42
    

    You can also work with it without unwrapping it:

    val test = 1.right()
    val testPlus10 = test.map { it + 10 } // adds 10 to `test` if it is `Right`, does nothing otherwise
    val x = testPlus10.getOrElse { 0 } // unwrap by providing a default value
    // x = 11
    

    For more example check the official docs.

    Recommended reading: How do I get the value out of my Monad