- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
collection with typed cells
Sun, 2011-06-05, 12:33
Hi,
I'm looking for a general collection that works as follows:
1. it contains a set of typed cells
2. each cell has its unique type C[T], where C is another collection
and T is a unique type
3. when an element with type T is added to the collection, the element
would be appended to C[T].
I tried to implement this myself, but:
1. I'm wondering why type test on type parameters doesn't work in
test1 and test2.
2. Is it possible to define a ImpDTCollection[TYPE LIST] class instead
of a set of ImpDTCollectionX?
With thanks
Jiansen
test1:
class ImpDTCollection2[A,B]{
var collectionA : List[A] = Nil
var collectionB : List[B] = Nil
def append(elem:Any) = elem match {
case elem:A =>
println("addA "+elem)
collectionA = elem :: collectionA
case elem:B =>
println("addB "+elem)
collectionB = elem :: collectionB
case _ =>
println("Not valid element")
Unit
}
}
object DTTest extends Application{
val c = new ImpDTCollection2[String, Float]
c.append(1)
c.append("HI")
println("hi")
}
output:
addA 1 //How?
addA HI
hi
test2:
class ImpDTCollection2[A,B]{
var collectionA : List[Int] = Nil
var collectionB : List[B] = Nil
def append(elem:Any) = elem match {
case elem:Int =>
println("addA "+elem)
collectionA = elem :: collectionA
case elem:B =>
println("addB "+elem)
collectionB = elem :: collectionB
case _ =>
println("Not valid element")
Unit
}
}
object DTTest extends Application{
val c = new ImpDTCollection2[Int, Float]
c.append(1)
c.append("HI")
println("hi")
}
output:
addA 1
addB HI // How?
hi