Scala尝试并捕获错误

时间:2015-06-19 17:53:13

标签: scala try-catch

所以这是我的代码:

def loadOperation(fileName:String): csvList = {
  try{
   val pattern = """^(.+);(\d{5});(4|2|31);(0|1);(.+);(\d+|\d+,\d+)$""".r
   Source.fromFile(fileName).getLines().foldLeft(List[CsvEntry]())((csvList, currentLine) =>
     currentLine match {
      case pattern(organisation,yearAndQuartal,medKF,trueOrFalse,name,money) => new CsvEntry(organisation,yearAndQuartal.toInt,medKF.toInt,trueOrFalse.toInt,name,money) :: csvList
      case default => csvList
      })
  } catch {
    case one: java.io.FileNotFoundException => println("This file could not be found!")
  }}

问题是我的代码不起作用,它总是显示以下错误:

  发现

类型不匹配:单位需要csvList哪个扩展为List [CsvEntry]?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

问题是catch子句:

println("This file could not be found!")

的类型为Unit,显然不是csvList。您应该添加一个返回空列表的附加行,例如

catch {
    case one: java.io.FileNotFoundException => println("This file could not be found!")
}

Nil