user1868607
user1868607

Reputation: 2600

Access member of underlying type of sequence (Scala)

package p {
 trait A{ type B }
}

trait C {
  val D: Seq[p.A]

  def m(t: D. ...) = ???
}

I would like to refer to type B through D. How can I do this?

Note

The code that I inherited was:

package p {
 trait A{ type B }
}

trait C {
  val D: p.A

  def m(t: D.B) = ???
}

This makes sense in that context and certainly compiles.

Upvotes: 0

Views: 88

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

This code uses path-dependent types.

trait A { type B }
class A1 extends A { type B = String }
class A2 extends A { type B = Int }

In each of these types implementation uses different type B. So you cannot just refer to type B directly, only through a path from the value.

trait Foo {
  type Bar
  def operationA(bar: Bar) = X
  def operationB(bar: Bar) = Y
}
val foo1: Foo = ...
val foo2: Foo = ...

Here I cannot know of foo1.Bar =:= foo2.Bar. I don't know anything about it. I only know that I could pass foo1.Bar into foo1.operationA or foo1.operationB and pass foo2.Bar into foo2.operationA or foo2.operationB.

This is used correctly in the original code because you are fixing D to be a specific immutable value (D). So the types working on this value are referring to it (D.B).

Seq of D cannot be used that way. You would have to do something like

package p {
 trait A{ type B }
}

trait C {
  val Ds: Seq[p.A]

  def m(D: p.A)(t: D. ...) = ???
}

and then while working on Ds passing each value of if into m first, followed by a value derived from it (so that it would have this D. ... type) next.

Upvotes: 1

Related Questions