Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what this scala symbol ->_ means

Tags:

scala

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

like image 927
igx Avatar asked Aug 28 '13 15:08

igx


People also ask

What is the use of symbol in Scala?

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.

What is symbol literal in Scala?

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 }


1 Answers

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.

like image 166
Travis Brown Avatar answered Nov 02 '22 19:11

Travis Brown