2012-12-07 50 views
2

我不明白为什么这个代码在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} 
    } 
} 

你能不能给我一些解释或良好的联系,以了解这些问题?

回答

3

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

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

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

但在功能的身体,你必须创建T类型的数组。

+0

嗯,也许我的例子是愚蠢的,在现实中getColumns可以返回其他数组类型,int或double,所以也许我的方法在这里不好或没有解决的办法? – reyman64

+0

@ reyman64我完成了我的答案。你更清楚吗? – paradigmatic

+0

确定它更清楚,感谢 – reyman64

0

你的函数签名要求的复合回报类型T,但你给它一个Array[Double]。请注意,T <: Array[Double],而不是相反。以下代码有效:

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

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

相关问题