2

So in Java I had a class that contained a HashMap that used the class as a key pointing to an object of the same class.

class ComponentContainer {
  private HashMap<Class<? extends Component>, Component> componentMap

  public ComponentContainer {
    componentMap = new HashMap<Class<? extends Component>, Component>();
  }

  public void set (Component c) {
    componentMap.put(c.getClass(), c);
  }
}

However when I try to do the same thing in Scala within a trait I find myself getting a type mismatch error that a java.lang.Class[?0] was found where Class[Component] was needed.

trait ComponentContainer {
  val componentMap: HashMap[Class[Component], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }    
}

This has me absolutely stumped any help would be appreciated greatly.

0

1 Answer 1

1

The reason your code doesn't compile is that T.getClass method has result Class[_] and not Class[T]. Details of getClass has been explained by VonC here.

From your source code I cannot see if you care about type parameter of Class instances but following version of your code compiles:

trait ComponentContainer {
  val componentMap: HashMap[Class[_], Component] = HashMap.empty

  def set (c: Component) {
    val t = (c.getClass, c)
    componentMap += t
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect, thank you. I don't think I'll have any reason to worry about type parameters of components. It all seems so obvious once someone points it out to you. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.