Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - overriding type-member with bounds

I have the following problem with hierarchy of traits in Scala code:

First of all, I have a basic trait MyTrait[A] with such definition:

trait MyTrait[A] {
  def v1: A
}

It is then followed by a definition of a trait Base with a type-member:

trait Base[A] {
  type T <: MyTrait[A]
  val baseV: T
}

And, at last, a trait Gen which overrides Base's type member.

trait Gen[A, X <: MyTrait[A]] extends Base[A] {
  type T = X
}

The problem is that in the Gen trait it seems that bounds of the type-member are lost. This can be proven by following tests:

Compiles:

trait Test1 {
  val x: Base[_]
  println(x.baseV.v1)
}

Doesn't compile (value v1 is not a member of Test2.this.x.T):

trait Test2 {
  val x: Gen[_, _]
  println(x.baseV.v1)
}

I would like to know whether it's a limitation of the language or there is a workaround it. Questions on similar topics on stackowerflow (1, 2) appear to be focusing on different aspects than mine and I am genuinely at a loss because I can't find much information about such behavior in Scala.

Scala code template of this question can be found on scastie

like image 707
a7emenov Avatar asked Dec 20 '18 20:12

a7emenov


1 Answers

This works:

trait Test2 {
  val x: Gen[A, X] forSome { type A; type X <: MyTrait[A] }
  println(x.baseV.v1)
}

I believe the issue is that

Gen[_, _]

Has to mean

Gen[_ >: Nothing <: Any, _ >: Nothing <: Any]

Which is the same as

Gen[A, X] forSome { type A; type X }

That is, even though the bounds on Gen say that X <: MyTrait[A], the wildcards do not inherit that bound. You can see a similar problem here:

trait Data { def data: String }
trait Box[A <: Data] { def data: A }
def unbox(b: Box[_]): String = b.data.data // nope; the wildcard is not <: Data

We can add the bounds to the wildcards explicitly. However, because the bound on the second wildcard depends on the first one, we are forced to use the extended forSome syntax for the existential, so we can name A and use it twice.

Gen[A, _ <: MyTrait[A]] forSome { type A }

And I opted to just put everything in the existential clause, which is equivalent:

Gen[A, X] forSome { type A; type X <: MyTrait[A] }

You can also use

Gen[_, _ <: MyTrait[_]]

but this is not equivalent, as it doesn't relate the left and right parameters. If Gen[A, _] contained an A in addition to a MyTrait[A], then using x: Gen[_, _ <: MyTrait[_]] would render the "bare" value and the "wrapped" value with incompatible types.

like image 133
HTNW Avatar answered Oct 26 '22 22:10

HTNW