我不明白为什么这个代码在Scala是不可能的:如何返回作为数组子类型的类型参数?
def getColumns[T <: Array[_]]():Array[(String,T)] ={
Array(Tuple2("test",Array(1.0,2.0,3.0)))
}
编译器说:
数组类型的表达式[(字符串,数组[双])不符合预期类型数组[(字符串,T)]
我有与此代码相同的错误:
def getColumns[T <: Array[Double]]():Array[(String,T)] ={
Array(Tuple2("test",Array(1.0,2.0,3.0)))
}
这是我的完整的使用情况更加清晰,最后我选择了Array[AnyVal]
:
class SystemError(message: String, nestedException: Throwable) extends Exception(message, nestedException) {
def this() = this("", null)
def this(message: String) = this(message, null)
def this(nestedException : Throwable) = this("", nestedException)
}
class FileDataSource(path:String) {
val fileCatch = catching(classOf[FileNotFoundException], classOf[IOException]).withApply(e => throw new SystemError(e))
def getStream():Option[BufferedSource]={
fileCatch.opt{Source.fromInputStream(getClass.getResourceAsStream(path))}
}
}
class CSVReader(src:FileDataSource) {
def lines= src.getStream().get
val head = lines.getLines.take(1).toList(0).split(",")
val otherLines = lines.getLines.drop(1).toList
def getColumns():Array[(String,Array[_])] ={
val transposeLines = otherLines.map { l => l.split(",").map {
d => d match {
case String => d
case Int => d.toInt
case Double => d.toDouble
}}.transpose }
head zip transposeLines.map {_.toArray}
}
}
你能不能给我一些解释或良好的联系,以了解这些问题?
嗯,也许我的例子是愚蠢的,在现实中getColumns可以返回其他数组类型,int或double,所以也许我的方法在这里不好或没有解决的办法? – reyman64
@ reyman64我完成了我的答案。你更清楚吗? – paradigmatic
确定它更清楚,感谢 – reyman64