“ #”操作符在 Scala 中是什么意思?

我在这个博客中看到这段代码:

// 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]中有一个我从未见过的操作员 #。既然很难搜索(被搜索引擎忽略) ,谁能告诉我这是什么意思?

16714 次浏览

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

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 (搜索“磅”)

为了解释它,我们首先要解释 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 中的另一个类中声明一个类时,你是说那个类的 每宗个案有这样一个子类。换句话说,没有 A.B类,但是有 a1.Ba2.B类,它们是 与众不同类,正如上面的错误消息告诉我们的那样。

如果您不了解这一点,请查找与路径相关的类型。

现在,#使您可以引用这样的嵌套类,而不必将其限制在特定的实例中。换句话说,没有 A.B,但有 A#B,这意味着 A任何实例的 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.

这里有一个用于搜索“符号运算符”(实际上是方法)的资源,但是我还没有弄明白如何在 scalex 中转义“ #”进行搜索

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