`#` 运算符在 Scala 中是什么意思? [英] What does the `#` operator mean in Scala?

查看:78
本文介绍了`#` 运算符在 Scala 中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此博客中看到此代码:键入-Scala 级编程:

I see this code in this blog: Type-Level Programming in 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] 中有一个我从未见过的操作符 #.既然很难搜索(被搜索引擎忽略),谁能告诉我这是什么意思?

There is an operator # in the code R#X[R#Next] which I've never seen. Since it's difficult to search it(ignored by search engines), who can tell me what does it mean?

推荐答案

要解释它,我们首先要解释 Scala 中的嵌套类.考虑这个简单的例子:

To explain it, we first have to explain nested classes in Scala. Consider this simple example:

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类,它们不同 类,正如上面的错误消息告诉我们的那样.

When you declare a class inside another class in Scala, you are saying that each instance of that class has such a subclass. In other words, there's no A.B class, but there are a1.B and a2.B classes, and they are different classes, as the error message is telling us above.

如果您不明白这一点,请查找路径依赖类型.

If you did not understand that, look up path dependent types.

现在,# 使您可以引用此类嵌套类,而无需将其限制为特定实例.换句话说,没有AB,但有A#B,这意味着anyB嵌套类A 的实例.

Now, # makes it possible for you to refer to such nested classes without restricting it to a particular instance. In other words, there's no A.B, but there's A#B, which means a B nested class of any instance of A.

我们可以通过更改上面的代码看到这一点:

We can see this in work by changing the code above:

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.

这篇关于`#` 运算符在 Scala 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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