0
votes

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
  }
}
3
Which one is throwing the error? Are all these fields of type Option[T]? - Yuval Itzchakov
The code you posted doesn't make much sense. Post all the relevant stuff. - The_Tourist

3 Answers

1
votes

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

0
votes

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.

0
votes

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.