Scala: Declare val in if condition

  • A+
Category:Languages

I have very generic use case. I have a method conditionMethod which return Int

def conditionMethod(..):Int = {..} 

Now I have if condition using same method

if (conditionMethod(..) > 0){   conditionMethod(..) + 23 // Any action } 

Problem is it is calling method conditionMethod two times. To solve this, another approach is

val tmp = conditionMethod(..) if (tmp > 0){   tmp + 23 // Any action } 

What I don't like in this is I have to define a variable with larger scope.

Can I do something like

if ((val tmp = conditionMethod(..)) > 0){  // tmp variable in if condition itself    tmp + 23 // Any action } 

Scala version: 2.11

 


You can keep the scope really tight:

val result = {   val tmp = methodCall()   if (tmp>0) tmp else tmp+23 } 

Or use match

methodCall() match {    case x if x <= 0 => x + 23    case x => x } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: