Skip to content

Instantly share code, notes, and snippets.

@yureative
Created July 5, 2014 15:34
Show Gist options
  • Select an option

  • Save yureative/4e0c72b9fdc68c0b51da to your computer and use it in GitHub Desktop.

Select an option

Save yureative/4e0c72b9fdc68c0b51da to your computer and use it in GitHub Desktop.
sealed abstract class Gender
case object Male extends Gender
case object Female extends Gender
case class Person(name: String, age: Int, gender: Gender)
object CaseMatchExample extends App {
val people = List(
Person("yuu", 25, Male),
Person("mizuki", 27, Female),
Person("satoshi", 51, Male))
people foreach { person =>
person match {
case Person(name, _, Female) => println(s"$name is female")
case Person(name, age, Male) if age < 30 => println(s"$name is a young man")
case Person(name, _, _) => println(s"$name is a gentleman")
}
}
// The outputs
// yuu is a young man
// mizuki is female
// satoshi is a gentleman
// you can write more shortly like this
/*
people foreach {
case Person(...
case Person(...
case Person(...
}
*/
val foundPerson: Option[Person] = people.find(_.name == "yuki")
foundPerson match {
case None => println("can't find a person who has name yuki")
case Some(person) => println(s"yuki found! And his age is ${person.age}")
}
// you can write more shortly like this
/*
people.find(_.name == "yuki") match {
case None ...
case Some(...
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment