如何在Scala中返回None

如何在Scala中返回None,scala,design-patterns,nullable,Scala,Design Patterns,Nullable,对于我的第一个Scala程序,我正在尝试编写一个小实用程序,它将XML文件从一个模式转换为另一个模式 我开始编写一个方法,该方法将为我提供文件内容: def loadFile(filename: String, encoding: String = "utf-8"):Option[String] = { try { val source = scala.io.Source.fromFile(filename, encoding) val content

对于我的第一个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
    }

  }
但它不编译。我从行
返回None
的错误消息中返回“value apply不是Nothing的成员”和“value isDefinedAt不是Nothing的成员”

我能找到的所有返回选项的示例都使用匹配,但这在这里没有意义。如果我因为某种原因无法读取文件,我只想不失败

在这种情况下我该怎么办?在Scala中做这种事情有模式吗

关于
“catch”
有很多

在scala中,它应该是这样来编译的:

  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()
      Some(contents)
    } catch {
      case x: IOException =>  None
      case x => errorHandler(x) // if any other exception
    }
  }

  def errorHandler(e: Any) = None // put some logic here..
因此,请使用:

catch { case: x:ExceptionType ={ .. handling .. }}
在Scala中,catch是一个接受另一个函数作为参数的函数。所以,拥有你所拥有的东西会抱怨apply函数
case
提供了
catch
想要的功能(PartialFunction)。(简而言之)

注意:
Scala
甚至
IOException

中,所有异常都是
未选中的

 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
  {
    case e:Exception=>{
      return None
    }

  }
}

在这种特定情况下(异常处理),我建议改用

然而,我建议不要捕捉异常。返回
None
:这是
FileNotFoundException
吗?标准的
IOException
?是否有错误消息(
不支持的编码
浮现在脑海中…)

我的经验法则是让调用方处理异常。如果他不在乎错误本身,那么处理事情就像:

Try {loadFile("test.txt")}.toOption
更好的是,由于
Try
具有所有必需的方法,因此它可以以一种非常简洁的方式用于理解:

for(s <- Try {loadFile("test.txt")};
    i <- Try {s.toInt}) yield i

for(s,但我同意+Nicolas Rinaudo的风格-让调用方决定如何处理错误,不管是什么。不过,有时,在将错误发送回调用方之前,您需要在调用方处理一些事情(如清理缓存或任何要清理的事情)。
for(s <- Try {loadFile("test.txt")};
    i <- Try {s.toInt}) yield i