home search about rss feed twitter ko-fi

JIT: Using Option and Try in for-Expressions (Scala 3 Video)

Before we get into the next TDL lesson, I need to make sure you’re familiar with how the Option, Try, and Either error-handling types work in for expressions.

Option

When you have a function like this that returns an Option:

import scala.util.control.Exception.allCatch

def makeInt(s: String): Option[Int] =
    allCatch.opt(s.toInt)

You can use that function in a for expression to yield a result:

val rez: Option[Int] = 
    for
        a <- makeInt("1")
        b <- makeInt("2")
        c <- makeInt("3")
    yield
        a + b + c

// rez == Some(6)

To make this simpler, let’s get rid of makeInt and replace it with just Some values:

val rez: Option[Int] = 
    for
        a <- Some(1)
        b <- Some(2)
        c <- Some(3)
    yield
        a + b + c

As shown in that code, I declare that rez has the type Option[Int]. When you use one or more Option values in a for/yield expression, the resulting value will also be an Option, as indicated there. So that’s the first important thing to know:

When a for expression works with Option values and yields a result, that result is also an Option.

A second key to know is that inside the for expression and yield area, the values a, b, and c have the “success” type that’s inside the Option. Restating this second key point:

Inside the for and yield areas, the values a, b, and c have the data type that’s inside the Option. In those two areas you work with the “success” type that’s contained within the Option.

Try works the same way

And then a third important thing to know is that Try works the same as Option:

import scala.util.{Try, Success, Failure}

val rez: Try[Int] = 
    for
        a <- Success(1)
        b <- Success(2)
        c <- Success(3)
    yield
        a + b + c

// rez == Success(6)

In this for expression the same two keys apply:

  • When a for expression works with Try values and yields a result, the result is a Try.
  • Inside the for and yield areas, the values a, b, and c have the “success” data type that’s inside the Try. (In those two areas you work with that success type.)

(For many more details, see my book, Functional Programming, Simplified.)

Update: All of my new videos are now on
LearnScala.dev