Hi, im new to scala and ran into the following problem:
I want to get a subcollection of an existing collection that only contains elements of a specific type. The following works:
class C(val name : String)
class D(name : String) extends C(name) { }
val collection = Set[C](new C("C1"),new D("D1"),new C("C2"),new D("D2"))
collection.collect{case d : D => d}.size must be === 2 // works
But when i try to extend the collection classes with a method "onlyInstancesOf[Type]" this does not work. First my implementation:
object Collection {
implicit def extendScalaCollection[E](coll : Traversable[E]) = new CollectionExtension[E](coll)
}
class CollectionExtension[E](coll : Traversable[E]) {
def onlyInstancesOf[SpecialE <: E] : Traversable[SpecialE] = {
coll.collect({case special : SpecialE => special}).asInstanceOf[Traversable[SpecialE]]
}
}
So when i use this extension and execute:
collection.onlyInstancesOf[D].size must be === 2
I get an error that .size returned 4 and not 2. Also, i checked, the result actually contains C1 and C2 though it should not.
When i do:
collection.onlyInstancesOf[D].foreach(e => println(e.name))
I get the exception:
java.lang.ClassCastException: CollectionsSpec$$anonfun$1$C$1 cannot be cast to CollectionsSpec$$anonfun$1$D$1
So obviously the resulting set still contains the elements that should have been filtered out.
I dont get why this happens, can anyone explain this?
Edit: Scala: Scala code runner version 2.8.0.final