24
votes

I'm using the Option Type's isEmpty method to check if there is no value. I do not want to use the case match as in my situation, I just want to check if there is None as I would throw an error to the caller. But the isEmpty method fails even though the value is None.

Here is what I tried!

val questionOption = Question.getQuestionForQuestionId(userExam.get.examId, currQuesId + 1)

if(questionOption.isEmpty) {
    Left(Failure(FailureCode.NO_DATA_FOUND, "Cannot get next exam question you tampered your cookie or cookie is lost.... >> TODO... modify the exception message"))
} 

It is not getting inside the if condition. I tried to do a println on the questionOption and it prints None. So wondering why I'm not getting inside the if condition.

2
Can you show some code replicating this issue?Don Roby
case object None extends Option[Nothing] { def isEmpty = true; ...}Prince John Wesley
You are probably doing something wrong or the description of the problem is misleading. If you will paste None.isEmpty into the REPL it will return true.Piotr Kukielka
What do you mean with "isEmpty method fails"? isEmpty return true for None, as opposite as isDefined: perhaps you got confused?Marco
What I noticed is that it is getting inside the if condition but I'm returning from inside the if condition. The return type of the method is an Either. How come it is not returning? Am I missing something here?joesan

2 Answers

24
votes

From the comment under the question, the real problem emerges:

 val questionOption = Question.getQuestionForQuestionId(userExam.get.examId, currQuesId + 1) 
 if(questionOption.isEmpty) { 
   Left(Failure(FailureCode.NO_DATA_FOUND, "Cannot get next exam question you tampered your cookie or cookie is lost.... >> TODO... modify the exception message")) 
 }

By itself, if returns type Unit so that your statement is returning nothing useful. If you want to return something you need to add in either an else which then returns the least upper bound of the result types. Hence

 >>> val yo = if(1 != 0) 4
 yo: Unit

 >>> val ya = if(1 != 0) Left(1) else Right("got it")
 ya: Either[Int, String]
14
votes

You could just do a boolean check to see of the value is None and throw the error to the caller if it is, otherwise continue processing:

scala> val o: Option[Any] = None
o: Option[Any] = None

scala> println(o == None)
true

scala> println(o != None)
false

But maybe a better way to accomplish what you're trying to do, alert the caller of the error or continue processing, would be to use Scala's Try idiom to handle errors.