Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Declare val in if condition

Tags:

scala

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

like image 561
user811602 Avatar asked Jan 24 '19 07:01

user811602


2 Answers

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
}
like image 101
Thilo Avatar answered Nov 04 '22 11:11

Thilo


Starting Scala 2.13, the chaining operation pipe can be used to convert/pipe a value with a function of interest, and thus avoids an intermediate variable:

import scala.util.chaining._

13.pipe(res => if (res > 0) res else res + 23 ) // 13

This is actually a very close variant of a match statement and can as well be written as such:

-27 pipe { case res if (res > 0) => res case res => res + 23 } // -4
like image 26
Xavier Guihot Avatar answered Nov 04 '22 09:11

Xavier Guihot