简体   繁体   中英

Scala: What is :: in { case x :: y :: _ => y}? Method or case class?

object Test1 extends App {
    val list: List[Int] => Int = {
        case x :: y :: _ => y    //what is ::? method or case class?
    }
    println(list(List(1, 2, 3)))    //result is 2.
}

I set "syntax coloring" in scala IDE, foreground color of method I set Red. code snapshot: 在此处输入图像描述 And I can't open declaration of black:: , so I don't know what it is.

If black:: is method, it should be called by this way:

... {case _.::(y).::(x) => y}     //compile failed!

So, What is black:: ? method or case class?

Thanks a lot!

I think it's a method as described here . For history's sake, in case that page goes away, here's the blurb:

About pattern matching on Lists

If you review the possible forms of patterns explained in Chapter 15, you might find that neither List(...) nor:: looks like it fits one of the kinds of patterns defined there. In fact, List(...) is an instance of a library-defined extractor pattern. Such patterns will be treated in Chapter 24. The "cons" pattern x:: xs is a special case of an infix operation pattern. You know already that, when seen as an expression, an infix operation is equivalent to a method call. For patterns, the rules are different: When seen as a pattern, an infix operation such as p op q is equivalent to op(p, q). That is, the infix operator op is treated as a constructor pattern. In particular, a cons pattern such as x:: xs is treated as::(x, xs). This hints that there should be a class named:: that corresponds to the pattern constructor. Indeed there is such as class. It is named scala.:: and is exactly the class that builds non-empty lists. So:: exists twice in Scala, once as a name of a class in package scala, and again as a method in class List. The effect of the method:: is to produce an instance of the class scala.::. You'll find out more details about how the List class is implemented in Chapter 22.

So it's scala.::(a,b)

Here Sequence pattern is applied.

case x:: y:: _ => y

means, the passed sequence first value is mapped to x and second value is mapped to y and all remaining values are applied with wildcard pattern (_).

Here finally the case returns y means second value.

another ex: case x:: y:: z:: _ => z

this case returns third element from the sequence.

another ex: case _:: _:: z:: _ => z

in this example first and second element are used underscore as we don't need THESE elements hence replaced with _.

Also it throws Exception if the passing list size is less than what it expects, for Example the below throws exception:

val third: List[Int] => Int = {case _ :: _ :: z :: _ => z}

third(List(1, 2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM