jeudi 6 octobre 2016

Scala type mismatch between parent and child objects (Java-defined class Class is invariant in type T)

I have a (Scala) object hierarchy like so:

class Vehicle {
    ...
}

class Car extends Vehicle {
    ...
}

class Motorcycle extends Vehicle {
    ...
}

etc. I have a method that takes some input and returns the class type of the Vehicle subclass that is "best suited for it":

def chooseVehicleType(fizz : String) : Class[_ <: VehicleType] = {
    fizz match {
        case "buzz"     =>    classOf[Car]
        case "foo"      =>    classOf[Motorcycle]
        // etc.
        case _          =>    throw new UnsupportedOperationException(s"We don't support ${fizz} yet.")
    }
}

The problem here is that I get compiler errors on the classOf assignments:

type mismatch; found : Classcom.me.myapp.model.Car required: Class[com.me.myapp.model.Vehicle] Note: com.me.myapp.model.Car <: com.me.myapp.model.Vehicle, but Java-defined class Class is invariant in type T. You may wish to investigate a wildcard type such as _ <: com.me.myapp.model.Vehicle. (SLS 3.2.10)

Any ideas as to what is going on here, and what the fix is?





Aucun commentaire:

Enregistrer un commentaire