检查选项[长]中的空值

  • 本文关键字:空值 选项 scala
  • 更新时间 :
  • 英文 :


我是Scala的新开发人员,我想写一个简单的函数:

def compute_start(start: Option[Long]) : (Int, Int, Int) = {
if (start != null.asInstanceOf[Long] && start != null && start != "null") { // I tried ALL THOSE OPTIONS !!!
var result = helper(start.get) // another function
(temp._1, temp._2, temp._3)
} else {
(0, 0, 0)
}

但我总是收到此错误:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 696.0 failed 8 times, most recent failure: Lost task 0.7 in stage 696.0 (TID 99422, ldatanode10ch.nms.ld, executor 145): java.util.NoSuchElementException: None.get

所以,我猜条件如果(start != null.asInstanceOf[Long]没有返回true。

请问,如何避免长(或选项[长](变量的空值? 谢谢!

您可以像这样使用模式匹配:

def compute_start(start: Option[Long]) : (Int, Int, Int) = {
start match {
case Some(value) => 
val result = helper(value)
(result._1, result._2, result._3)
case None => (0,0,0)
}
}

编辑:
多考虑一下您的问题,我相信您的start值正在作为null传递,这是一些奇怪的 Java 库的副作用,该库将此值传递给您的函数。
处理它的一种方法是确保 Optional 值如下所示:

// simulated value got from your library (must probably)
val start: Option[Long] = null
// ensure the start value is safe (without null values)
val safeStart = Option(start).filter(_.nonEmpty).flatten
// Now you should get a safe result
val result = compute_start(start)

包装null(Option(x)(,然后解开包装 (.flatten(,然后按照标准Option[Long]继续。

def compute_start(start: Option[Long]) : (Int, Int, Int) =
Option(start).flatten.fold((0, 0, 0)){ startVal =>
val result = helper(startVal) // don't use var's
(temp._1, temp._2, temp._3)
}

您可以在start上进行模式匹配,以安全地测试start是否有值并将其提取到变量(long(,然后像在 if 语句中一样使用它。

def compute_start(start: Option[Long]) : (Int, Int, Int) = start match {
case Some(long) => {
var result = helper(long) // another function
(temp._1, temp._2, temp._3)
}
case None    => (0,0,0)
}

您的错误是NoSuchElementException,而不是NullPointerException。特别是错误消息

java.util.NoSuchElementException: None.get

表示您正在None上调用get,可能在此行中(但您应该从堆栈跟踪中看到(:

var result = helper(start.get)

当然,如果startNone,那么它不等于0L(0.asInstanceOf[Long]的结果(、null"null",因此您的任何检查都不起作用。

因此,要解决此问题,您应该像其他答案所说的那样进行模式匹配。如果在这种情况下你得到NullPointerException并且它仍然来自这个地方,我的猜测是startSome(null)。你可以像这样处理它

def compute_start(start: Option[Long]) : (Int, Int, Int) = {
start match {
case Some(value) if value != null => 
val result = helper(value)
(result._1, result._2, result._3)
case _ => (0,0,0)
}
}

案例_涵盖以前case不匹配的任何内容,包括Some(null)null

最新更新