Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a HashMap as a subclass in scala?

I've created the following class:

class Foo[T] extends collection.mutable.HashMap[T, Int] {...}

(The class has some methods, but to reproduce this problem it doesn't need any.)

When I clone an instance of this class and try to use it as another instance of Foo, I get the following type error:

scala> val f = new Foo[String]
f: Foo[String] = Map()

scala> val anotherF: Foo[String] = f.clone
<console>:9: error: type mismatch;
found   : scala.collection.mutable.HashMap[String,Int]
required: Foo[String]

How do I cast the result of f.clone as an instance of Foo[String] ?

Update A commenter pointed out that I could override the clone method on HashMap. No objections to doing so, but it seems like I should be able to do so without reimplementing the actual cloning process.

like image 509
brahn Avatar asked Nov 23 '25 02:11

brahn


1 Answers

The HashMap class returns HashMap objects, whether it is extended or not. If you want to change the return value, you have to extend MapLike as well.

like image 94
Daniel C. Sobral Avatar answered Nov 24 '25 20:11

Daniel C. Sobral