Scala:如果条件声明val

use*_*602 7 scala

我有非常通用的用例.我有一个conditionMethod返回Int 的方法

def conditionMethod(..):Int = {..}
Run Code Online (Sandbox Code Playgroud)

现在我有条件使用相同的方法

if (conditionMethod(..) > 0){
  conditionMethod(..) + 23 // Any action
}
Run Code Online (Sandbox Code Playgroud)

问题是它调用方法conditionMethod两次.为了解决这个问题,另一种方法是

val tmp = conditionMethod(..)
if (tmp > 0){
  tmp + 23 // Any action
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢的是我必须定义一个范围更大的变量.

我能做点什么吗

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

Scala版本:2.11

Thi*_*ilo 10

您可以保持范围非常紧密:

val result = {
  val tmp = methodCall()
  if (tmp>0) tmp else tmp+23
}
Run Code Online (Sandbox Code Playgroud)

或者使用 match

methodCall() match {
   case x if x <= 0 => x + 23
   case x => x
}
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 7

启动时Scala 2.13,链接操作pipe可用于转换/管道具有感兴趣功能的值,从而避免使用中间变量:

import scala.util.chaining._

13.pipe(res => if (res > 0) res else res + 23 ) // 13
Run Code Online (Sandbox Code Playgroud)

这实际上是一个非常接近的match语句变体,也可以这样编写:

-27 pipe { case res if (res > 0) => res case res => res + 23 } // -4
Run Code Online (Sandbox Code Playgroud)