Scala: Railway programming fold

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

--

--

--

On a continuing learning journey..

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Making a RTS game #6: Improving the UI (Unity/C#)

Design Pattern — Builder

Caring about your code

How to open a csv file in Pycharm?

Raider Wolves (EN)

Strong Opinions Usually Hurt

Clean Coding: Step Two

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Learn

Learn

On a continuing learning journey..

More from Medium

Scala: Partial function argument in collect api

Type Classes in Scala 2

Understanding Implicit Parameters (with a Primer on Currying)

Polymorphic functions in Scala