我的特征变量可以接受多种数据类型{Int, Long, String, Double}
。
我需要对此变量进行一些数学运算。因此,我尝试将变量转换为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
}
现在,由于我需要对此进行一些操作,以尝试将ArrayBuffer转换为其各自的类型。
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
}
我在打印语句上显示错误
Any does not take parameters
print(v(i))
^
v
是ArrayBuffer类的,所以我假设它应该使用一个整数参数来返回该索引处的元素。 (我还假设,如果a(0)
是Int
,v
是ArrayBuffer [Int]
。还是ArrayBuffer [Any]
?)。
谁能解释我所理解的错误吗?
答案 0 :(得分:3)
println
语句返回Unit
。因此,v
的类型被推断为ArrayBuffer[Int]
和Unit
的下界,即Any
。
您可以按以下步骤解决此问题:
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 _ => a
}
for (i <- b) print(v(i) + " ")
}
或类似这样:
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 _ => throw new IllegalArgumentException("Unexpected type")
}
for (i <- b) print(v(i) + " ")
}
,但是在两种情况下,它都不会给您带来任何好处,因为您可以分配给v
的最特定类型仍然是ArrayBuffer[_]
之类。您必须在比赛的 中使用其他类型信息来做一些事情,否则就没用了。
答案 1 :(得分:0)
v
的类型为Any
。
您还需要使case _ => ...
返回ArrayBuffer
。