在 Scala 选项类型 isEmpty 方法中检查 None

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20843594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:58:20  来源:igfitidea点击:

Check for None in Scala Option type isEmpty method

scalascala-option

提问by sparkr

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

我正在使用 Option Type 的isEmpty方法来检查是否没有值。我不想casematch在我的情况下使用as,我只想检查是否存在,None因为我会向调用者抛出错误。但是isEmpty即使值为 ,该方法也会失败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.

它没有进入 if 条件。我试图在 questionOption 上做一个 println 并且它打印 None 。所以想知道为什么我没有进入 if 条件。

采纳答案by wheaties

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, ifreturns type Unitso that your statement is returning nothing useful. If you want to return something you need to add in either an elsewhich then returns the least upper bound of the result types. Hence

就其本身而言,if返回类型Unit以便您的语句不返回任何有用的信息。如果你想返回一些你需要添加的东西else,然后返回结果类型的最小上限。因此

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

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

回答by axiopisty

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:

您可以只进行布尔检查以查看值是否为 None ,如果是,则将错误抛出给调用者,否则继续处理:

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 Tryidiom to handle errors.

但也许更好的方法来完成你正在尝试做的事情,提醒调用者错误或继续处理,是使用 Scala 的Try成语来处理错误。