Scala: for-comprehension contexts do not mix

Learn
2 min readJan 27, 2022

--

In a scala for-comprehension, you cannot have left assignment operators against different contexts. That is if you are in an Either context, all your left arrows have to be in the Either context. If you are in the Option context, all your left arrows have to be in the Option context. They are like Oil and Water, they do not mix.

Demonstrating this would be pretty easy and might be the best way to have that sink in. First, let us see that two options can be put together in a for-comprehension, and that two eithers can be put together in a for-comprehension.

val optionOne = Some(1)
val optionTwo = Some(2)
val eitherOne = Right(1)
val eitherTwo = Right(2)
println(for {
a <- optionOne
b <- optionTwo
} yield a + b)
println(for {
a <- eitherOne
b <- eitherTwo
} yield a + b)
Some(3)
Right(3)

Now, let us see that an Either and an Option cannot be put together in a for-comprehension and see the corresponding compiler error.

val optionOne = Some(1)
val optionTwo = Some(2)
val eitherOne = Right(1)
val eitherTwo = Right(2)
println(for {
a <- optionOne
b <- eitherTwo
Found: Either[Nothing, Int]
Required: Option[Any]
} yield a + b)

When the for-comprehension tries to do a left assignment from an Either after having done a left assignment from an Option, the compiler says that it expects an Option and cannot take an Either.

Align the return types of the functions you intend to use within left arrows in a for-comprehension

Having realized that you cannot mix the contexts in a for-comprehension, you can now let this context restriction drive the signature for new functions that you intend to use in left arrow assignment operators. Options, Eithers, EitherTs, OptionTs are all to some extent equivalent, and interchangeable. If you want to use such a function within a for-comprehension, then let the left assignment operations that you already have inform the return type for newly added methods.

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

No responses yet