我想要一个函数 readFile
,它将变量 file
作为输入。文件可以是 string
或 java.io.File
。假设有一个函数 readJavaFile
接受一个 java.io.File
作为输入。
我想做这样的事情:
def readFile(file:Either[String, File]) = {
file match {
case s:String => readJavaFile(new File(s))
case s:File => readJavaFile(s)
}
}
什么是正确的实现方式?我在 SO 上看到了类似的问题,但它们指的是更复杂的情况。
编辑:
恐怕 Either
不是遵循的方式。我希望能够将该函数调用为:
readFile(s)
其中 s
是一个字符串或 readFile(f)
其中 f
是一个 File
编辑: 这是我的真实代码:
def csvread(file: File,
separator: Char=',',
quote: Char='"',
escape: Char='\\',
skipLines: Int = 0): DenseMatrix[Double] = {
val input = new FileReader(file)
var mat = CSVReader.read(input, separator, quote, escape, skipLines)
mat = mat.takeWhile(line => line.length != 0 && line.head.nonEmpty) // empty lines at the end
input.close()
if(mat.length == 0) {
DenseMatrix.zeros[Double](0,0)
} else {
DenseMatrix.tabulate(mat.length,mat.head.length)((i,j)=>mat(i)(j).toDouble)
}
}
def csvread(file: String,
separator: Char=',',
quote: Char='"',
escape: Char='\\',
skipLines: Int = 0): DenseMatrix[Double] = csvread(new File(file), separator, quote, escape, skipLines)
我想称它为:
package breeze.linalg
/**
* Created by donbeo on 07/02/16.
*/
import org.scalatest._
import org.scalatest.junit._
import org.scalatest.prop._
import org.junit.runner.RunWith
import breeze.linalg.csvread
import java.io.File
@RunWith(classOf[JUnitRunner])
class ReadCsvTest extends FunSuite with Checkers{
test("Try readcsv") {
val f = csvread(new File("/Users/donbeo/Documents/datasets/glass.csv"))
val v = csvread("/Users/donbeo/Documents/datasets/glass.csv")
}
}
但我收到错误信息:
Error:(41, 16) in package object linalg, multiple overloaded alternatives of method csvread define default arguments.
package object linalg {
^
最佳答案
对我来说,这听起来像是重载的完美案例。
def readFile(s:String) = readJavaFile(new File(s))
def readFile(f:File) = readJavaFile(f)
除非您已经在 Either
中拥有字符串或文件,否则将它们放入 Either
中只是为了再次将它们取出似乎比需要的更复杂。
关于java - scala 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35255053/