3

Say I have the following simple Scala definition of a trait inside a class:

class Foo {
  trait Bar
}

val f = new Foo
type MyAlias = f.Bar

This lets me alias Bar with MyAlias. However, if I try to inline that to read type MyAlias = (new Foo).Bar the compile complains. Why does it complain and is there a way to achieve this in one line?

Kvass
  • 8,294
  • 12
  • 65
  • 108

1 Answers1

4

The . operator with types in Scala is used for path-dependent types. For example, your f.Bar is an instance of Bar that has f as its parent. The compiler forbids (new Foo).Bar because it isn't a useful expression - you throw away the only Foo that can be used to create Bar instances of that type, so no value would ever be able to satisfy that alias.

What you may have wanted was Foo#Bar. This is not a path-dependent type. Any Bar, no matter what Foo is is associated with, is a Foo#Bar.

Here is an example:

class Foo {
  class Bar
}

val f1 = new Foo
val f2 = new Foo
val b1 = new f1.Bar
val b2 = new f2.Bar

// This won't compile, because b2 is a f2.Bar, not an f1.Bar
// val pathDependentBar: f1.Bar = b2

val FooHashBar: Foo#Bar = b1
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52