gpt4 book ai didi

arrays - 如何返回作为数组子类型的类型参数?

转载 作者:行者123 更新时间:2023-12-04 05:20:15 25 4
gpt4 key购买 nike

我不明白为什么这段代码在 Scala 中是不可能的:

  def getColumns[T <: Array[_]] ():Array[(String,T)] ={
Array(Tuple2("test",Array(1.0,2.0,3.0)))
}

编译器说:

Expression of type Array[(String,Array[Double])] doesn't conform to expected type Array[(String, 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}
}
}

你能给我一些解释或好的链接来理解这些问题吗?

最佳答案

因为您的函数必须能够与任何 T 一起使用(任何数组类型),但是,它将始终返回 Array[(String,Array[Double])] .

一个更简单的工作签名是:

def getColumns[T](): Array[(String,Array[T])]

但是在函数体中,您必须创建一个类型为 T 的数组。 .

关于arrays - 如何返回作为数组子类型的类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13766848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com