[Scala] For-Yield with Guards

mj park
2 min readJan 10, 2021

--

Highlights

  • How to generate a list with For-Yield
  • Can I apply “guards” in For-Yield ?

Problem

I want to generate a list of variables with certain conditions.

Solution

Before I introduce “For-Yield with guards”, let’s revisit the basic for-yield loop and see what it does

Basic For-Yield Loop

In case you are new to yield, you can think of it as below

  • When the for-yield loop begins, it will create a temporary bucket that is the same type as the initial collection.
  • For each iteration, the output is store in the bucket.
  • When all iterations are finished, the contents of the bucket are returned
val list = for (i <- 0 to 5) yield i// this will return Vector(0,1,2,3,4,5)

For-Yield Loop with Guards

In addition to “yielding” a new collection from the initial collection, we can also apply “guards” to for-yield loop. This is typically used when you want to filter out the values based on specific condition(s).

My preferred syntax is to use curly brackets, { }

for {
CONDITION(S)
} yield SOMETHING

Example code below:

# Case 1 - using a ternary operator// creating a list of even numbers
val
foo = for (i <- 1 to 10 if (i % 2 == 0)) yield i
// re-writing the code using "Guards"
val
bar = for {
i <- 1 to 10
if (i % 2 == 0)
} yield i
// multiple conditions
val woo = for {
i <- 1 to 100
if (i % 2 == 0)
if (i > 10 && i < 40)
if (i % 4 == 0)
} yield i

Well, hope this helps everyone out there who is enthusiastic about Scala. Thanks for reading! :)

--

--

mj park
mj park

Written by mj park

Software Engineer | Scala | Functional Programming

No responses yet