home search about rss feed twitter ko-fi

foreach Method (Scala 3 Video)

Keys:

  • The Scala foreach method is available on all collections, and it’s used to iterate over a collection and run your algorithm
  • foreach is always used for side effects, like printing and updating `var fields
  • foreach is the same as a basic for loop

Usage, and simplifications:

val ints = List(1, 2, 3)
ints.foreach((i:Int) => println(i))     // long, with data type
ints.foreach(i => println(i))           // long
ints.foreach(println(_))
ints.foreach(println)

Anonymous functions (function literals):

// this part is an anonymous function:
ints.foreach((i: Int) => println(i))
             ----------------------

Using a “named” function:

def printAnInt(i: Int): Unit = println(i)
val ints = List(1, 2, 3)
ints.foreach(printAnInt)

Writing our own foreach function:

// Int
def foreach(xs: Seq[Int], f: Int => Unit): Unit =
    for x <- xs do f(x)

// Generic
def foreach[A](xs: Seq[A], f: A => Unit): Unit =
    for x <- xs do f(x)

A multiline foreach example:

val ints = List(1, 2, 3)
ints.foreach { i =>
    // can use multiple lines here
    val x = i * 10
    println(x)
}

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