record4s

Pattern Matching

Using select

Pattern matching is provided via select.

import com.github.tarao.record4s.select

val person = %(name = "tarao", age = 3, email = "tarao@example.com")
// person: % {
//   val name: String
//   val age: Int
//   val email: String
// } = %(name = tarao, age = 3, email = tarao@example.com)

person match {
  case select.name.age(name, age) =>
    println(s"${name} (${age})")
}
// tarao (3)

Nested pattern matching works of course.

val pattern = "(.*)@(.*)".r
// pattern: Regex = (.*)@(.*)

person match {
  case select.name.email(name, pattern(user, _)) =>
    val isSame = if (name == user) "the same" else "not the same"
    println(s"name and email user name are ${isSame}")
}
// name and email user name are the same

Named pattern matching

Named pattern matching something like this is currently not yet supported.

person match {
  case %(name = name, age = age) => ???
}

We need language improvement discussed on SIP-43 to implement this kind of thing.