Search code examples
javafunctional-programmingmonadseithervavr

Unbox value from Either<L, R> vavr


Background

I have a small function that can return Either<String, Float>. If it succeed it returns a float otherwise an error string.

My objective is to perform a series of operations in a pipeline, and to achieve railway oriented programming using Either.

Code

import java.util.function.Function;
import io.vavr.control.Either;

@Test
public void run(){

    Function<Float, Either<String, Float>> either_double = num -> {
        if(num == 4.0f)
            Either.left("I don't like this number");
        return Either.right(num * 2);
    };

    Function<Float, Float> incr = x -> x + 1.0f;

    Float actual = 
       Either.right(2f)
        .map(incr)
        .map(either_double)
        .get();

    Float expected = 6.0f;

    assertEquals(expected, actual);
}

This code does a series of simple operations. First I create a either of right with value 2, then I increment it and I finish by doubling it. The result of these operations is 6.

Problem

The result of the mathematical operations is 6.0f, but that's not what I get. Instead I get Right(6.0f).

This is an issue that prevents the code from compiling. I have a value boxed inside the Either Monad, but after checking their API for Either I didn't find a way to unbox it and get the value as is.

I thought about using getOrElseGet but even that method returns a Right.

Question

How do I access the real value stored inside the Either Monad?


Solution

  • Use flatMap(either_double) instead of map(either_double).