我想要一個功能readFile
,它需要輸入一個變量file
。文件可以是string
或java.io.File
。假設有一個功能readJavaFile
接受java.io.File
作爲輸入。scala模式匹配
我想要做的事,如:
def readFile(file:Either[String, File]) = {
file match {
case s:String => readJavaFile(new File(s))
case s:File => readJavaFile(s)
}
}
什麼是實現這個正確的方式?我看到類似的問題,但他們指的是更復雜的情況。
編輯: 恐怕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 {
^
Ta。我會刪除我的評論(這在一分鐘內) –