can someone assist me understanding this code
case "Foo" Foo(data) -> _ => { /*.. implementation */}
I see the usage of Foo.unapply(data) but I don't understand what this part
-> _
how and when to use it
Symbols are used to establish bindings between a name and the entity it refers to, such as a class or a method. Anything you define and can give a name to in Scala has an associated symbol.
A symbol literal 'x is a shorthand for the expression scala. Symbol("x") . Symbol is a case class, which is defined as follows. package scala final case class Symbol private (name: String) { override def toString: String = "'" + name }
It looks like someone is being way too clever for their own good. Suppose I've got the following:
case class Foo[A](command: String, data: A)
object -> { def unapply[A, B](p: (A, B)) = Some(p) }
Now I can write this:
scala> Foo("foo", (42, 'whatever)) match {
| case "foo" Foo(data) -> _ => data
| }
res0: Int = 42
Thanks to the magic of Scala's infix patterns, this is equivalent to the following:
Foo("foo", (42, 'whatever)) match {
case Foo("foo", data -> _) => data
}
Except that the infix version is guaranteed to confuse and annoy your code's future readers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With