Reputation: 59
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
}
}
Upvotes: 0
Views: 12247
Reputation: 5048
The return types of a,b,c
are all Option
, 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
Upvotes: 2
Reputation: 29193
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
.
Upvotes: 1
Reputation: 39587
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.
Upvotes: 1