在Scala中`#`运算符是什么意思?

我在这个博客中看到了这个代码: Scala中的Type-Level Programming :

// define the abstract types and bounds trait Recurse { type Next <: Recurse // this is the recursive function definition type X[R <: Recurse] <: Int } // implementation trait RecurseA extends Recurse { type Next = RecurseA // this is the implementation type X[R <: Recurse] = R#X[R#Next] } object Recurse { // infinite loop type C = RecurseA#X[RecurseA] } 

在我从未见过的代码R#X[R#Next]中有一个运算符# 。 由于很难search它(被search引擎忽略),谁能告诉我这是什么意思?

为了解释它,我们首先必须在Scala中解释嵌套的类。 考虑这个简单的例子:

 class A { class B def f(b: B) = println("Got my B!") } 

现在让我们尝试一下:

 scala> val a1 = new A a1: A = A@2fa8ecf4 scala> val a2 = new A a2: A = A@4bed4c8 scala> a2.f(new a1.B) <console>:11: error: type mismatch; found : a1.B required: a2.B a2.f(new a1.B) ^ 

当你在Scala中的另一个类中声明一个类时,你就是说这个类的每个实例都有这样的子类。 换句话说,没有AB类,但有a1.Ba2.B类,它们是不同的类,正如错误信息在上面告诉我们的。

如果你不明白,查找path依赖types。

现在, #使您可以引用这样的嵌套类而不将其限制到特定的实例。 换句话说,没有AB ,但是有A#B ,这意味着B任何实例的B嵌套类。

我们可以通过更改上面的代码来看到这个工作:

 class A { class B def f(b: B) = println("Got my B!") def g(b: A#B) = println("Got a B.") } 

并尝试一下:

 scala> val a1 = new A a1: A = A@1497b7b1 scala> val a2 = new A a2: A = A@2607c28c scala> a2.f(new a1.B) <console>:11: error: type mismatch; found : a1.B required: a2.B a2.f(new a1.B) ^ scala> a2.g(new a1.B) Got a B. 

它被称为types投影,用于访问types成员。

 scala> trait R { | type A = Int | } defined trait R scala> val x = null.asInstanceOf[R#A] x: Int = 0 

基本上,这是一种引用其他类中的类的方法。

http://jim-mcbeath.blogspot.com/2008/09/scala-syntax-primer.html (search“磅”)

这里有一些search“符号运算符”(这实际上是方法)的资源,但我还没有想出如何在scalex中search“#”

http://www.artima.com/pins1ed/book-index.html#indexanchor

http://scalex.org/

    Interesting Posts