Scala's '::' operator, how does it work?

前端 未结 4 1029
死守一世寂寞
死守一世寂寞 2020-11-29 00:27

In Scala, I can make a caseclass, case class Foo(x:Int), and then put it in a list like so:

List(Foo(42))

Now, nothing strange

4条回答
  •  甜味超标
    2020-11-29 00:54

    One aspect missing in the answers given is that to support :: in pattern matching expressions:

    List(1,2) match {
      case x :: xs => println(x + " " + xs)
      case _ => println("")
    }
    

    A class :: is defined :

    final case class ::[B](private var hd: B, private[scala] var tl: List[B]) 
    

    so case ::(x,xs) would produce the same result. The expression case x :: xs works because the default extractor :: is defined for the case class and it can be used infix.

提交回复
热议问题