Destructuring in when

In pattern matching you can a) match against values inside a structure (hence the term) and b) extract values from the matched expression.

So if we had a data class called Person, we could do

when(person) {
  Person("sam", age) -> println("This matches all sams and makes $age available as a parameter")
  Person(name, _) -> println("This matches all persons, and makes $name a parameter and ignores the age")
}

and various combinations of that kind of thing.

In Scala if you use a literal, then it will be matched against that value, if you use a variable name it will extract the value and assign it to the variable, and if you use a variable name inside backticks it will match against the value of an already defined variable (but that variable must be ‘constant’).

4 Likes