为什么选择带有散列而不是点的 Scala 类型成员? [英] Why does one select Scala type members with a hash instead of a dot?

查看:35
本文介绍了为什么选择带有散列而不是点的 Scala 类型成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中,从类中选择类型的语法与从类中选择任何其他类型的语法不同.因为前者使用散列作为选择运算符而不是点.这是为什么?

In Scala, the syntax for selecting a type from a class is different from that of selecting anything else from a class. In that the former uses a hash as the selection operator instead of a dot. Why is that?

示例:如果我们有一个这样的类......

Example: If we have a class like so...

class Example {
    type Foo = String
}

我们为什么要从类中选择这样的类型...

Why do we select the type from the class like this...

val example:Example#Foo = "1"

而不是这样?

val example:Example.Foo = "1"

推荐答案

Example#Foo 被称为类型投影,将匹配任何类型FooExample 类型的任何封闭实例的代码>.如果您编写类型 Example.Foo,编译器将查找名为 Examplevalue(而不是 type)> 并将仅引用其封闭的 Foo 类型.这通常用于单例对象的上下文中.

Example#Foo is called a type projection and will match any type Foo of any enclosing instance of type Example. If you write a type Example.Foo, the compiler will look for the value (and not type) called Example and will refer to its enclosing Foo type only. This is often used in the context of singleton objects.

例如:

object MyEnum extends Enumeration {
  val EnumValue = Value
}

val e: MyEnum.Value = MyEnum.EnumValue

如果 Scala 使用 . 进行类型投影,这将导致混淆,因为前面的标识符可以被解释为类型或值……因此 #.请注意,正如@kassens 所写,Java 只有在这方面具有类型投影.

If Scala used . for type projections, this would lead to confusion because the preceding identifier could be interpreted either as a type or as a value… Hence the #. Note that, as @kassens writes, Java only has type projections in that respect.

这篇关于为什么选择带有散列而不是点的 Scala 类型成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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