Declaring multiple variables in Scala

The trivial answer is to declare them as tuples:

val (a, b, c) = (1, 2, 3)

What might be interesting here is that this is based on pattern matching. What is actually happens is that you are constructing a tuple, and then, through pattern matching, assigning values to a, b and c.

Let’s consider some other pattern matching examples to explore this a bit further:

val DatePattern = """(\d{4})-(\d\d)-(\d\d)""".r
val DatePattern(year, month, day) = "2009-12-30"
val List(rnd1, rnd2, rnd3) = List.fill(3)(scala.util.Random.nextInt(100))
val head :: tail = List.range(1, 10)

object ToInt {
  def unapply(s: String) = try {
    Some(s.toInt)
  } catch {
    case _ => None
  }
}

val DatePattern(ToInt(year), ToInt(month), ToInt(day)) = "2010-01-01"

Just as a side note, the rnd example, in particular, may be written more simply, and without illustrating pattern matching, as shown below.

val rnd1, rnd2, rnd3 = scala.util.Random.nextInt(100)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)