小编Due*_*ist的帖子

使用 Source.fromResource 从文件读取时处理 NullPointerException

Source.fromResource()从不存在的文件读取时,我的方法出现了奇怪的行为。据我了解,它应该返回,null所以我将它包装到Option. 但是当匹配它时,它被识别为Some并且我得到了NullPointerException

ReadFromFileExample.scala:

object ReadFromFileExample extends App {

  import scala.io.Source

  val sourceOpt = Option(Source.fromResource("non_existing_file.txt"))

  assert (sourceOpt.isDefined) // but it should return false

  sourceOpt match {
    case Some(source) => source.getLines()
    case None => throw new RuntimeException("Error reading from file")
  }

}
Run Code Online (Sandbox Code Playgroud)

如何解释这种行为?

UPD

我错了。它应该返回null类型的非值BufferedSource。但我怀疑它可以返回nulltype 的值BufferedLineIterator。我不明白它是如何返回NullPointerExceptionBufferedLineIterator

scala

2
推荐指数
1
解决办法
2175
查看次数

标签 统计

scala ×1