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

前端 未结 4 918
死守一世寂寞
死守一世寂寞 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:48

    From the Spec:

    6.12.3 InfixOperations An infix operator can be an arbitrary identifier. Infix operators have precedence and associativity defined as follows.

    ...

    The associativity of an operator is determined by the operator’s last character. Operators ending in a colon ‘:’ are right-associative. All other operators are left- associative.

    You can always see how these rules are applied in Scala by printing the program after it has been through the 'typer' phase of the compiler:

    scala -Xprint:typer -e "1 :: Nil"
    
    val r: List[Int] = {
       val x$1: Int = 1;
      immutable.this.Nil.::[Int](x$1)
    };
    

提交回复
热议问题