Scala: Railway programming fold

Learn
2 min readJan 17, 2022

--

Railway programming, which is about having functions return a success and failure output explicitly accounting for errors in the system may eventually get into a state from where there is no further need for capturing error and success tracks separately. Total functions returning an Either[Success, Failure] is good. However total functions that would always return a valid output without ever returning a failure is even better. So, you might need to get from the two-tracked either context into the single track of total functions.

That is where fold comes in.

val greenEither = Either.cond(true, "green", "red")
println(greenEither.fold(_ => "Red track", _ => "Green track"))

fold has two arguments, first argument is a function that takes the left side of the either and you can return whatever you want, and the second argument is a function that takes the right side of the either and returns whatever you want.

The code snippet above would print “Green track”, as the Either has the condition of true and the second argument of the fold method would get executed.

Green track

Just to demonstrate that you can the function arguments of the fold method return whatever type you want, the below snippet has two separate fold implementations returning different types.

println("... Green Either..")
val greenEither = Either.cond(true, "green", "red")
println(greenEither.fold(_ => "Red track", _ => "Green track"))
println(greenEither.fold(_ => 0 , _ => true))
... Green Either..
Green track
true

If the either had evaluated to false for the condition, the two tracks would have got folded into the red track as demonstrated below.

println("... Red Either... ")

val redEither = Either.cond(false, "green", "red")
println(redEither.fold(_ => "Red track", _ => "Green track"))
println(redEither.fold(_ => 0, _ => true))
... Red Either...
Red track
0

--

--

Learn
Learn

Written by Learn

On a continuing learning journey..

No responses yet