Tutorial by Examples

x and y are extracted from the tuple: val (x, y) = (1337, 42) // x: Int = 1337 // y: Int = 42 To ignore a value use _: val (_, y: Int) = (1337, 42) // y: Int = 42 To unpack an extractor: val myTuple = (1337, 42) myTuple._1 // res0: Int = 1337 myTuple._2 // res1: Int = 42 Note that...
A case class is a class with a lot of standard boilerplate code automatically included. One benefit of this is that Scala makes it easy to use extractors with case classes. case class Person(name: String, age: Int) // Define the case class val p = Person("Paola", 42) // Instantiate a v...
A custom extraction can be written by implementing the unapply method and returning a value of type Option: class Foo(val x: String) object Foo { def unapply(foo: Foo): Option[String] = Some(foo.x) } new Foo("42") match { case Foo(x) => x } // "42" The retur...
If a case class has exactly two values, its extractor can be used in infix notation. case class Pair(a: String, b: String) val p: Pair = Pair("hello", "world") val x Pair y = p //x: String = hello //y: String = world Any extractor that returns a 2-tuple can work this way....
A regular expression with grouped parts can be used as an extractor: scala> val address = """(.+):(\d+)""".r address: scala.util.matching.Regex = (.+):(\d+) scala> val address(host, port) = "some.domain.org:8080" host: String = some.domain.org por...
Extractor behavior can be used to derive arbitrary values from their input. This can be useful in scenarios where you want to be able to act on the results of a transformation in the event that the transformation is successful. Consider as an example the various user name formats usable in a Window...

Page 1 of 1