简体   繁体   English

三元运算符无法正常运行

[英]Ternary operator is not working scala

I'm trying to make a ternary operator in scala but actually it seems that the '?' 我正在尝试在Scala中创建一个三元运算符,但实际上似乎是'?' character cannot be resolved 字符无法解析

here is the completed method 这是完整的方法

object Credit {
  def getMaximumWeek(orderId: Int, locale: String): Int = {
    val orderCompletedHistoryCount = Order.getOrderCompletedHistoryCount(orderId, locale);
   orderCompletedHistoryCount == 0 ? 0: Order.getMaximumAllowedWeeks(orderId, locale)
  }
}

referenced to this link , I'm getting an error connot resolve symbol '?' 引用此链接出现错误无法解析符号“?” even both method are returning integers 即使两个方法都返回整数

Scala does not have a ternary operator , like the ? Scala没有像的三元运算符 ? operator C++ has for example, so the error is expected, regardless of what the two operadans return. 例如,C ++运算符具有这种运算符,因此无论两个操作数返回什么,都会出现该错误。

Use an if-else expression instead, like this: 改用if-else表达式,如下所示:

if(orderCompletedHistoryCount == 0)
    0
else
    Order.getMaximumAllowedWeeks(orderId, locale)

You can use Scalaz for that. 您可以为此使用Scalaz The only difference is it requires | 唯一的区别是它需要| sign instead of : sign. 签署而不是:签署。

import scalaz.Scalaz._

false ? "Yes" | "No" // returns No

It's not only for booleans, you can try it with Option objects as well: 它不仅适用于布尔值,还可以与Option对象一起尝试:

None ? "Defined" | "Empty" // returns Empty

You should add the following line to build.sbt in order to use it: 您应该将以下行添加到build.sbt以便使用它:

libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.2.16"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM