Home »
Code Examples »
Scala Code Examples
Scala - Matching on Case Classes Code Example
The code for Matching on Case Classes
case class Student(name: String, age: Int)
val alex = new Student("Alex", 21)
val alvin = new Student("Alvin", 20)
val mark = new Student("Mark", 18)
for (std <- List(alex, alvin, mark)) {
std match {
case Student("Alex", 21) => println("Hi Alex")
case Student("Alvin", 20) => println("Hi Alvin")
case Student(name, age) =>
println("Hello, " + name + " (" + age + " year-old person)")
}
}
/*
Output:
Hi Alex
Hi Alvin
Hello, Mark (18 year-old person)
*/
Code by IncludeHelp,
on August 8, 2022 01:21