'In Scala, how can i declare right type in base abstract class to access by index in this situation
I'm sorry, I'm very new to Scala.
My code looks like below.
abstract class A{
val container: Any
//Some other member and methods are hidden
}
class B extends A {
val container: Vector(1,2)
//Some other member and methods are hidden
}
class C extends A {
val container: ArrayBuffer(1,2,3)
//Some other member and methods are hidden
}
So, when i want use these function in main function like below, which means that i intend to access container by index.
val vector = new ArrayBuffer[A].empty
vector += new B
vector += new C
for( vec <- vector ){
println(vec.container(0))
}
However, the compiler says "Any does not take parameters"
So, my problem is, how should i declare value container in base class to access input with index.
Help me, Thanks.
Solution 1:[1]
There are at least 2 variants:
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.Vector
import scala.collection.IndexedSeq
// variant 1
trait A1[T] {
def container: IndexedSeq[T]
}
class B1 extends A1[Int] {
val container: Vector[Int] = Vector(1, 2)
}
class C1 extends A1[Long] {
val container: Vector[Long] = Vector(1, 2)
}
// variant 2
trait A2 {
def container: IndexedSeq[_]
}
class B2 extends A2 {
val container: Vector[Int] = Vector(1, 2)
}
class C2 extends A2 {
val container: ArrayBuffer[Long] = ArrayBuffer(1, 2)
}
object Main extends App {
val coll1 = new ArrayBuffer[A1[_]]()
coll1 += new B1()
coll1 += new C1()
val coll2 = new ArrayBuffer[A2]()
coll2 += new B2()
coll2 += new C2()
for( vec <- coll1 ) {
println(vec.container(0))
}
for( vec <- coll2 ) {
println(vec.container(0))
}
}
tested here on Scala 2.13.6
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
