对于我的第一个Scala程序,我试图编写一个小的实用程序,该实用程序会将XML文件从一种模式转换为另一种模式。
我开始写一个可以给我文件内容的方法:
def loadFile(filename: String, encoding: String = "utf-8"):Option[String] = {
try
{
val source = scala.io.Source.fromFile(filename, encoding)
val contents = source.mkString
source.close()
return Some(contents)
}
catch
{
return None
}
}
但是它不能编译。我从行
return None
收到错误消息,返回“value apply不是Nothing的成员”和“value isDefinedAt不是Nothing的成员”的错误消息。我可以找到的所有返回Option的示例都使用匹配,但这在这里没有意义。如果我由于某种原因无法读取文件,我只是想不失败。
在这种情况下我该怎么办?在Scala中有做这种事情的模式吗?
最佳答案
在这种特定情况下(异常处理),我建议改为使用Try。
def loadFile(filename: String, encoding: String = "utf-8"):Option[String] = {
Try {
val source = scala.io.Source.fromFile(filename, encoding)
val contents = source.mkString
source.close()
return Some(contents)
}.toOption
}
但是,我建议不要完全捕获异常。您通过返回
None
来消除错误的原因:这是FileNotFoundException
吗?标准的IOException
?是否有错误消息(想到Unsupported encoding
…)?我的经验法则是让调用者处理异常。如果他不关心错误本身,那么处理事情就很简单:
Try {loadFile("test.txt")}.toOption
更好的是,由于
Try
具有所有必需的方法,因此可以以一种相当整洁的方式将其用于理解:for(s <- Try {loadFile("test.txt")};
i <- Try {s.toInt}) yield i
这将导致
Success[Int]
或Failure
包含一个异常,准确描述出了什么问题。
关于scala - 如何在Scala中返回None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19690589/