2

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!

4
  • return null from the catch block Commented Feb 25, 2014 at 23:54
  • I tried that but it gave me a type mismatch Commented Feb 25, 2014 at 23:55
  • is Data in the deque of primitive type or an Object ? Commented Feb 25, 2014 at 23:56
  • class LinkedDeQue[A] extends Deque[A] Commented Feb 25, 2014 at 23:57

2 Answers 2

8

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

My list is empty when last = null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.