I have a variable of a trait that accepts multiple datatypes {Int, Long, String, Double}.
I need to do some math operation on this variable. So I try to convert the variable to an ArrayBuffer [Any].
def toArray (x: MultiV): ArrayBuffer [Any] = {
val a = new ArrayBuffer[Any]()
for (i <- 0 until rows) a += x(i) // x(i) belongs to set {Int, Long, String, Double}
a
}
Now as I need to perform some operations on this try to convert ArrayBuffer to their individual types.
def printInd (a: ArrayBuffer [Any], b: Seq[Int]) = {
val v = a(0) match {
case _: Double => a.asInstanceOf [ArrayBuffer [Double]]
case _: Int => a.asInstanceOf [ArrayBuffer [Int]]
case _: Long => a.asInstanceOf [ArrayBuffer [Long]]
case _: String => a.asInstanceOf [ArrayBuffer [String]]
case _ => println ("printInd: type not supported")
}
for (i <- b) print(v(i) + " ") // Error: Any does not take parameters
}
I get an error on the print statement saying
Any does not take parameters
print(v(i))
^
v is of class ArrayBuffer so I am assuming it should take an integer parameter to return the element at that index. (Also I assume, if a(0) is Int, v is ArrayBuffer [Int]. Or is it still ArrayBuffer [Any]?).
Can anyone please explain what I am understanding wrong.
a.asInstanceOf[...]toval v.MultiVshould be a generic type. It looks like the values you extract into the buffer will all be of the same type (allDoubleor allIntetc.). Can you make that an explicit type parameter?