Search code examples
scalafor-comprehension

Executing side effect code inside scala for-comprehension block


How can I execute a side-effect code inside for-comprehension block? If I have something like this:

for {
 data <- fetchData()
} yield data.someAttribute

...and now I want to execute some code using foreach

for {
     data <- fetchData()
     someList <- fetchList(data)
     somelist.foreach(....)
} yield data.someAttribute

Solution

  • Simply:

    for {
         data <- fetchData()
         someList <- fetchList(data)
         _ = somelist.foreach(....)
    } yield data.someAttribute