Scala的'::'运算符,它如何工作? [英] Scala's '::' operator, how does it work?

查看:120
本文介绍了Scala的'::'运算符,它如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我可以创建一个caseclass,case class Foo(x:Int),然后将其放在这样的列表中:

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

List(Foo(42))

现在,这里没什么奇怪的.以下对我来说很奇怪.运算符::是列表上的函数,对吗?使用Scala中带有一个参数的任何函数,我都可以用中缀表示法来调用它. 一个示例是1 + 2是对象Int上的函数(+).我刚刚定义的类Foo没有::运算符,那么怎么可能呢?

Now, nothing strange here. The following is strange to me. The operator :: is a function on a list, right? With any function with one argument in Scala, I can call it with infix notation. An example is 1 + 2 is a function (+) on the object Int. The class Foo I just defined does not have the :: operator, so how is the following possible?

Foo(40) :: List(Foo(2))

在Scala 2.8 RC1中,我从交互式提示中获得以下输出:

In Scala 2.8 RC1, I get the following output from the interactive prompt:

scala> case class Foo(x:Int)
defined class Foo

scala> Foo(40) :: List(Foo(2))
res2: List[Foo] = List(Foo(40), Foo(2))

我可以继续使用它,但是解释是什么?

I can go on and use it, but what is the explanation?

推荐答案

摘自规范:

6.12.3 InfixOperations infix运算符可以是任意运算符 标识符.中缀运算符有 优先级和关联性 如下.

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.

在通过编译器的'typer'阶段打印程序后,您始终可以看到这些规则如何在Scala中应用:

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] = {
  <synthetic> val x$1: Int = 1;
  immutable.this.Nil.::[Int](x$1)
};

这篇关于Scala的'::'运算符,它如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆