简体   繁体   English

scala.MatchError:在scala上为null

[英]scala.MatchError: null on scala

I am getting the following error .. scala.MatchError: null 我收到以下错误.. scala.MatchError:null

Is there something wrong with my code ? 我的代码有问题吗? And if so, how do I fix it ? 如果是这样,我该如何解决?

val a : Option[String] = {
  company.customUrl match {
    case Some(a) => company.a
    case None => null
  }
}

val b :Option[String] = {
  company.b match {
    case Some(b) => company.b
    case _ => null
  }
}

val c : Option[Long] = {
  company.c match {
    case Some(c) => Option(company.c.get.toLong)
    case _ => null
  }
}

The return types of a,b,c are all Òption , but the raw type null in every second case is not. a,b,c的返回类型都是Òption ,但每隔第二种情况的原始类型null都不是。 Try to return None instead. 尝试返回None

a second case should catch all with _ a第二种情况应该抓住所有_

b can also be simplified to val b :Option[String] = company.b b也可以简化为val b :Option[String] = company.b

In your first case, you must have a null value for customUrl : 在第一种情况下,您的customUrl必须为null值:

scala> (null: Any) match { case Some(x) => x ; case None => ??? }
scala.MatchError: null
  ... 29 elided

It's considered better to wrap nullable values in Option as soon as possible and not to unwrap them. 最好尽快在Option中包装可为空的值,而不要对其进行包装。 In particular, don't set Options to null. 特别是,请勿将“选项”设置为null。

Option is meant to completely avoid null . Option是为了完全避免null Something that is Option should never be null ; Option永远不应为null instead, it should be None . 相反,它应该为None Therefore, you should not be doing this strange dance: 因此,您不应该做这种奇怪的舞蹈:

val a: Option[String] = company.customUrl match {
  case Some(a) => company.a
  case None => null
}

Just val a = company.customUrl will do. 只是val a = company.customUrl就可以了。

This is also likely the cause of the MatchError . 这也可能是MatchError的原因。 One or more of company.customUrl , company.b , or company.c is null , due to some other piece of your code. 由于代码的其他部分, company.customUrlcompany.bcompany.c一个或多个为null

Reiterating: Option should never be null . 重申: Option永远不能为null Furthermore, in Scala, always try to avoid null and prefer Option . 此外,在Scala中,请始终尝试避免使用null并更喜欢Option

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM