Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18158

Covariant typing in method param

I have the following classes:

abstract class Record {}

class Record1 extends Record {}

class Record2 extends Record {}

class MyTable[T <: Record : Manifest] extends externalLibrary.Table[T] {
    def method {}
}

object MyTable1 extends MyTable[Record1] {}

object MyTable2 extends MyTable[Record2] {}

And now I'm trying to accept any MyTable subclass in a method parameter

def testMethod[T <: MyTable[Record]](t: T) {
    t.method
}

val test = method(MyTable1)

This produces the error that MyTable1 does not conform to T. If I change the method to [T >: MyTable[Record]] then this satisfies the type checker at the calling point, but then of course I can't access t.method anymore. How would I fix this problem?

Upvotes: 1

Views: 81

Answers (1)

Luigi Plinge
Luigi Plinge

Reputation: 51109

You make classes covariant with a variance annotation at the declaration site:

class MyTable[+T <: Record : Manifest]

Upvotes: 3

Related Questions