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 becomes none if value null, or some(...) value otherwise
  • similarly when wrapping may throw exception in try, becomes either failure exception, or success value
  • tooption method converts try option in straightforward way: failure becomes none, success becomes some
  • in for-comprehension if any of 4 options returns none (i.e. 1 of them null of failed parse number), whole statement returns none, , if each of 4 yields value, passed yellowaccount constructor

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -