I am trying put together a "registry" of Companion Objects - by storing them in a List which is bound using Generics.
An example is best:
trait Foo
case class A() extends Foo
object A
case class B() extends Foo
object B
case class C() extends Foo
object C
trait HasFoos {
def allFoos: List[ _ <: Foo.type]
}
case class FooLookup() extends HasFoos {
def allFoos = List(A,B,C)
}
The error reported on FooLookup "def allFoos" is
- type mismatch; found : A.type required: Foo.type
What does the HasFoos.allFoos need to look like, or alternatively, what does the List(A,B,C) need to look like.
I tried def allFoos: List[ _ <: Foo]
as well; however it errors as well, and, I do want to work with the "Companion Object" not the class - I am sure I need some more generic's sugar dust around it but am not sure what it requires.
thanks in advance.
def allFoos: List[ _ <: Foo.type]
is unnecessary due to Scala's type variance.List
in scala is covariant, which means you can type-safely assign, for example,List[String]
to a variable of typeList[Any]
- something you could never do in Java. – ghik