Why does one select Scala type members with a hash instead of a dot?
Asked Answered
P

1

38

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"
Prologue answered 13/7, 2011 at 8:22 Comment(0)
C
47

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.

Claiborne answered 13/7, 2011 at 8:35 Comment(1)
Note that Java only has type projections. The type system of Java can not guarantee that a class returns an instance of an inner class of the same instance (same outer instance: this.Inner vs. any outer instance: Outer#Inner).Commorant

© 2022 - 2024 — McMap. All rights reserved.