Scala/Java错误处理NullPointerException

use*_*040 2 java error-handling scala try-catch nullpointerexception

我正在研究一种从双链接双端队列中获取元素的方法.当链表是空的时候,我得到一个nullpointerexception,我试图弄清楚如何处理它.我正在使用以下代码,但它仍然需要我返回A.任何想法我怎么能得到这个编译?

def peekBack():A = {
  try {
    last.data // return if the list is full if not, catch the nullpointerexception
  } catch {
    case ex: NullPointerException => {
      println("There are no elements in this list.")
         //Error is here, it is requiring me to return something!!!
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

gou*_*ama 8

如果last有些人var最终会null在某个时刻出现,那么简单的如果:

def peekBack(): A = {
  if (last == null) 
    throw new NoSuchElementException("empty list")
  else last.data
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想要返回null,你需要一个可以A为空的证明:

def peekBack()(implicit ev: Null <:< A): A = {
  if (last == null) ev(null)
  else last.data
}
Run Code Online (Sandbox Code Playgroud)

当然,正确的方法是返回Option[A]:

def peekBack(): Option[A] = Option(last).map(_.data)
Run Code Online (Sandbox Code Playgroud)