I have the following Scala code:
// 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
}
When this runs I get the following compiler error on the ternary operator:
/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"
Obviously the desired behavior could be rewritten as:
var qualifier : String = null
if(runMode.eq(RunMode.CLIENT_MODE)) {
qualifier = "whistle"
} else {
qualifier = "feather"
}
But why am I getting this error? What's the fix?
There is no ternary operator in Scala. Use if-else
:
val qualifier : String = if (runMode eq RunMode.CLIENT_MODE) "whistle" else "feather"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.