0

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."). Commented Oct 6, 2016 at 22:35

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry @user3816201 - that was a copy n paste error on my parent. Please see my edits, my code does return Vehicle (not VehicleType) afterall and still complains with the compiler message listed above.
i just copied and pasted. it is already working on me. Are you using which version of scala?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.