2

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

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

编译器说:

Array[(String,Array[Double])] 类型的表达式不符合预期的 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}
  }
}

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

4

2 回答 2

3

但是,因为您的函数必须能够使用任何T(任何数组类型),所以它总是会返回一个Array[(String,Array[Double])].

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

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

但在函数体中,您必须创建一个 type 数组T

于 2012-12-07T16:28:59.593 回答
0

您的函数签名需要 aT在复合返回类型中,但您给它一个Array[Double]. 请注意T <: Array[Double],不是相反。以下代码有效:

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

不应该是你想要的,而只是为了阐述问题。

于 2012-12-07T16:53:16.230 回答