0
votes

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[_ <: Vehicle] = {
    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?

1
No, with this code you can't get this error (unless you are returning a Car instead of a Class somewhere in "etc.").Alexey Romanov

1 Answers

0
votes

Can you try to change method return type? I just changed VehicleType with Vehicle in method return type and worked on me.