I am working on a method which gets elements out of a double linked deque. When the linkedlist is empty, I get a nullpointerexception and I am trying to figure out how to handle it. I am using to following code but it still requires me to return A. Any ideas how I can get to this compile?
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!!!
}
}
}
Thanks!
If last
is some var
that ends up being null
at some point, what about a simple if:
def peekBack(): A = {
if (last == null)
throw new NoSuchElementException("empty list")
else last.data
}
Edit : if you do want to return null
, you need a proof that A
is nullable:
def peekBack()(implicit ev: Null <:< A): A = {
if (last == null) ev(null)
else last.data
}
Of course the proper way to do this would be to return an Option[A]
:
def peekBack(): Option[A] = Option(last).map(_.data)
You dont take a nullpointerexception when your list is empty. you take it when your object is not initialized. ensure that you call a "initialized" empty object or best, foresee that also in your method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.