带有枚举的Scala if else赋值运算符失败

时间:2017-03-13 17:00:16

标签: string scala ternary-operator

我有以下Scala代码:

// RunMode.scala
object RunMode extends Enumeration {
  val CLIENT_MODE = Value("CLIENT")
  val SERVER_MODE = Value("SERVER")
}

// Driver.scala
object MyApp extends App {
  // Don't worry about this too much, the point is we get a valid
  // instance of RunMode to work with
  val runMode : RunMode = getRunMode(args)

  val qualifier : String = if runMode.eq(RunMode.CLIENT_MODE) "whistle" else "feather"

  // rest of main omitted for brevity
}

当运行时,我在三元运算符上得到以下编译器错误:

/Users/myuser/myapp/src/main/com/me/myapp/Driver.scala:22: '(' expected but identifier found.
  val qualifier : String = if runMode.eq(RunMode.CLIENT_MODE) "whistle" else "feather"

显然,所需的行为可以改写为:

var qualifier : String = null
if(runMode.eq(RunMode.CLIENT_MODE)) {
  qualifier = "whistle"
} else {
  qualifier = "feather"
}

但为什么我会收到此错误?有什么问题?

1 个答案:

答案 0 :(得分:2)

Scala中没有三元运算符。使用if-else

val qualifier : String = if (runMode eq RunMode.CLIENT_MODE) "whistle" else "feather"