Scala: Create object only if it doesn't exist yet -


i'm new scala, , simple question, i'm struggling figure out how make object if 1 doesn't exist yet.

i query database, , find out if there's present, if so, store in object, otherwise create new one. in java know like

pushmessage push = null;  if(getfromdatabase() == null) {    push = new pushmessaage(param1, param2...); } else {    push = getfromdatabase(); } 

but, how do in scala. when try , same thing, tells me getfromdatabase() doesn't conform expected type null. similarly, tried doing pattern matching , doing like

val push = getfromdatabase match {    case some(pushmessage) => pushmessage    case none => new pushmessage(param1, param2...) } 

but, didn't work told me

constructor cannot instantiated expected type, found: some[a], expected: pushmessage

so, how do this? , appreciated.

i assume getfromdatabase returns either null or pushmessage, in order pattern match correctly, need wrap option:

val push = option(getfromdatabase) match {    case some(pushmessage) => pushmessage    case none => new pushmessage(param1, param2...) } 

or (bad style, gives understanding of how works):

// option(null) === none, option(notnull) === some(notnull): // same `if (x ne null) some(x) else none val pushmaybe: option[pushmessage] = option(getfromdatabase)  val push: pushmessage =    if (pushmaybe.isempty) new pushmessage(param1, param2...)   else pushmaybe.get 

you can simplify with:

val push = option(getfromdatabase).getorelse(new pushmessage(param1, param2...)) 

p.s. if getfromdatabase isn't external method, it's better rewrite returning option[pushmessage] instead of pushmessage, like:

def getfromdatabase = {   val rs = driver.getresulset(query)   if (!rs.isbeforefirst()) none else some(parse(rs)) } 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -