How to do null checks in Scala in an idiomatic way? -
case class account( val name: string, val uuid: string, val lat: double, val lng: double ) } object account { def create(row: row): option[yellowaccount] = { val name = row.getas[string]("store_name") val uuid = row.getas[string]("uuid") val lato = row.getas[string]("latitude") val lngo = row.getas[string]("longitude") // how do null checks here in idiomatic way? if (lato == null || lngo == null) { return none } some(yellowaccount(name, uuid, lato.todouble, lngo.todouble)) } }
lat/long compulsory fields in account
. how do null checks in idiomatic way?
you can use option
type handle null
values. wrap nullable value in option
, can pattern match on or else. in example, think concise way combine 4 nullable values for-comprehension:
import scala.util.try object account { def create(row: row): option[yellowaccount] = { { name <- option( row.getas[string]("store_name") ) uuid <- option( row.getas[string]("uuid") ) lato <- try( row.getas[string]("latitude").todouble ).tooption lngo <- try( row.getas[string]("longitude").todouble ).tooption } yield yellowaccount(name, uuid, lato, lngo) } }
edit
another thing here _.todouble
conversion, may throw exception if fails parse string, can wrap in try
instead (i updated code above).
edit2
to clarify what's happening here:
- when wrap value in
option
becomesnone
if valuenull
, orsome(...)
value otherwise - similarly when wrapping may throw exception in
try
, becomes eitherfailure
exception, orsuccess
value tooption
method convertstry
option
in straightforward way:failure
becomesnone
,success
becomessome
- in for-comprehension if any of 4
option
s returnsnone
(i.e. 1 of themnull
of failed parse number), whole statement returnsnone
, , if each of 4 yields value, passedyellowaccount
constructor
Comments
Post a Comment