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。我不明白它是如何返回NullPointerException的BufferedLineIterator
scala ×1