Lobsterrrr Lobsterrrr - 1 year ago 61
Scala Question

Check for null and substitute by 0

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

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

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

Answer Source

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)