简体   繁体   中英

scala.MatchError: null on scala

I am getting the following error .. 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. Try to return None instead.

a second case should catch all with _

b can also be simplified to val b :Option[String] = company.b

In your first case, you must have a null value for customUrl :

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. In particular, don't set Options to null.

Option is meant to completely avoid null . Something that is Option should never be null ; instead, it should be 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.

This is also likely the cause of the MatchError . One or more of company.customUrl , company.b , or company.c is null , due to some other piece of your code.

Reiterating: Option should never be null . Furthermore, in Scala, always try to avoid null and prefer Option .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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