if statement - In scala, check non nullity and apply method directly? -
with following definitions:
class test { var activated: boolean = false } def maybetest(): test = { if(...) { val res = new test if(...) res.activated = true } else null }
i having lot of if
structures one:
val myobject = maybetest() if(myobject != null && myobject.activated) { // not care object }
i condensate little bit. there nice way define/write avoid nullpointerexception:
if(maybetest() &&> (_.activated)) { ... }
what best way of achieving in scala?
you can wrap such code in option this:
class test(num: int) { def somenum = num } val test: test = null option(test).map(t => t.somenum)
in example if variable null none, otherwise work some(value)
update
if don't want use option, can define such function
class test(num: int) { def give = num } def ifdefandtrue[t, k](obj: t)(iftrue: t => boolean)(then: => k) { if (obj != null && iftrue(obj)) }
in case this:
val test = new test // assuming activated false ifdefandtrue(test)(_.activate) { println("results in unit") }
but contains side effect , not functional