我有一个使用classTag的函数,而不是显式定义输入参数的数据类型。
例如,
def getColMult[T: ClassTag](A: Array[T], cols: Array[Int]): Array[Array[Double]] = {
if (cols.size == 1) {
var C = Array.apply(A.map{_(cols(0))})
C.transpose
}
else {
var C = Array.apply(A.map{_(cols(0))},A.map{_(cols(1))})
for (i <- (2 to cols.size - 1)) {
C = C ++ Array(A.map{_(cols(i))})
}
C.transpose
}
}
运行该函数时,会出现此错误:
名称:编译错误 消息:: 35:错误:T不带参数 var C = Array.apply(A.map(_(cols(0))})
console:39:错误:T不带参数。 var C = Array.apply(A.map {(cols(0))},A.map {(cols(1))})
答案 0 :(得分:1)
如果您将_()
替换为_.apply()
,则错误会更加清晰:
import scala.reflect.ClassTag
object Foo {
def getColMult[T: ClassTag](a: Array[T], cols: Array[Int]): Array[Array[Double]] = {
if (cols.size == 1) {
val c = Array(a.map({_.apply(cols(0))}))
c.transpose
} else {
val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++
(2 to cols.size - 1).flatMap({ i =>
Array(a.map({_.apply(cols(i))}))
})
c.transpose
}
}
}
给你
test.scala:6: error: value apply is not a member of type parameter T
val c = Array(a.map({_.apply(cols(0))}))
^
test.scala:9: error: value apply is not a member of type parameter T
val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++
^
test.scala:9: error: value apply is not a member of type parameter T
val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++
^
test.scala:11: error: value apply is not a member of type parameter T
Array(a.map({_.apply(cols(i))}))
顺便说一句,该代码看起来在功能上等同于
def getColMult2[T: ClassTag](a: Array[T], cols: Array[Int]): Array[Array[Double]] = {
val c = cols.map({col => a.map({_.apply(col)})})
c.transpose
}