Lobsterrrr Lobsterrrr - 2 months ago 6
Scala Question

Check for null and substitute by 0

I have the following statement which gets data from Redis DB using

client
. For some entries it returns
null
. How can I check for
null
and substitute it by
0
in a single line? Is there something similar to
getOrElse
? Or maybe I can somehow use
Option[String]
? I want to avoid using
if qty_str == null
.

val qty_str : String = Dress.up(client).hget("pk:"+ind,"qty")

Answer

The Option function turns a T which might be null into an Option[T]. Once you have that, you can use map to turn your Option[String] to an Option[Int], followed by getOrElse to replace None with your default value.

val qty_not_null : Option[String] = Option(qty_str)
val qty_int : Int = qty_not_null.map(_.toInt).getOrElse(0)
Comments