
First-Class Pattern Matching
I was reading through the Tour of Scala , interested in Scala’s fusion of functional programming and Java-style object-oriented programming, when I came across the concept of extractor objects . Essentially, a Scala object is a singleton class, and it comes with two methods you can define that - weirdly enough - can be used used for custom pattern matching: object CustomerID: def apply(name: String) = s"$name--23098234908" def unapply(customerID: String): Option[String] = val stringArray: Array[String] = customerID.split("--") if stringArray.tail.nonEmpty then Some(stringArray.head) else None val customer1ID = CustomerID("Sukyoung") // Sukyoung--23098234908 customer1ID match case CustomerID(name) => println(name) // prints Sukyoung case _ => println("Could not extract a CustomerID") Run this code! This caught me by major surprise as I was not aware any language yet had a way to support first-class pattern matching to any extent. ...


