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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With