Scala: Declare val in if condition
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
You could fold
over a single element collection.
Seq(conditionMethod(..)).fold(0){case (z,x) =>
if (x>z) x+23 // any action as long as the result is an Int
else x
}
If your "action" doesn't result in an Int
then you could use foldLeft
. Here's the same thing returning a String
.
Seq(conditionMethod(..)).foldLeft(""){case (_,x) =>
if (x>0) {
x+23 // any action as long as if/else types match
"string"
}
else "xxx"
}