So this is a fairly direct port of this Java question to scala
We have a bunch of traits that take generic parameters as follows:
trait Ident { }
trait Container[I <: Ident] {
def foo(id: I): String
}
trait Entity[C <: Container[I], I <: Ident] {
def container: C
def foo(id: I) = container.foo(id)
}
This works but it's a little clumbsy, since we have to provide the type of the Ident and the type of the Container when defining a sub-class of Entity. When in fact just the type of the Container would be enough type information by itself:
class MyIdent extends Ident { }
class MyContainer extends Container[MyIdent] { }
class MyEntity extends Entity[MyContainer,MyIdent] { }
// ^^^^^^^ shouldn't really be necessary
Using an existential type avoids the need for Entity to take two parameters ... but of course you can't refer to it later on.
trait Entity[C <: Container[I] forSome { type I <: Ident }] {
def container: C
def foo(id: I) = container.foo(id)
// ^^^ complains it has no idea what 'I' is here
}
Similarly converting the thing to use member types also doesn't work ...
trait Ident { }
trait Container {
type I <: Ident
def foo(id: I): String
}
trait Entity {
type C <: Container
def container: C
def foo(id: C#I) = container.foo(id)
// ^^ type mismatch
}
So does anyone know if there's an elegant solution to this problem in Scala?
container
aval
? – Cornet