Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala尝试捕获错误_Scala_Try Catch - Fatal编程技术网

Scala尝试捕获错误

Scala尝试捕获错误,scala,try-catch,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

这是我的代码:

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展开为列表[CsvEntry]


如何解决此问题?

问题在于
catch
子句:

println("This file could not be found!")
具有类型
单元
,显然不是
csvList
。您应该添加一个返回空列表的附加行,例如

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

Nil

cvsList
的定义是什么?您可以将其作为函数返回类型,但也可以在默认情况下将其作为值。抱歉:“type csvList=csvList[Entry]”val list:csvList=list()“当您捕获
FileNotFoundException
时,您可以使用
println
打印错误消息。因此,类型将是
Unit
。这没有意义,在默认情况下,您将它用作值、foldLeft的参数和表达式的返回值。在范围中是否有一些实例也被命名为csvList?是的,我定义了一个空列表,然后我用正则表达式从一个输入文件中捕获东西并将其添加到我的csvList…所以我将CsvEntries添加到我的csvList。问题出在哪里?谢谢!也可以返回列表吗?但在这种情况下,我认为零是更好的解决方案!你指的是来自
foldLeft
的列表吗?如果发生FNFE,它甚至不会到达
foldLeft
部分,因此
Nil
在这里可以。