Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
568 views
in Technique[技术] by (71.8m points)

syntax - Why does one select Scala type members with a hash instead of a dot?

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"

instead of like this?

val example:Example.Foo = "1"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

For instance:

object MyEnum extends Enumeration {
  val EnumValue = Value
}

val e: MyEnum.Value = MyEnum.EnumValue

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...