Scala程序中的三元运算符用法 [英] Ternary operator usage in Scala program
问题描述
我有一个需要应用过滤器的对象数组。
I have a Array of Objects that I need to apply filter.
val filteredList = list.filter{ l => (pid == "") ? true : l.ProviderId.toUpperCase().contains(pid.toUpperCase()))}
此Scala编译器未编译代码。我收到像
1)值这样的错误?不是布尔值
的成员2)类型toUpperCase不是字符串的成员。
This code is not getting complied by Scala compiler. I am getting error like 1) value ? is not a member of boolean 2) type toUpperCase is not a member of string.
有人可以帮助我如何在过滤器中编写此三元运算符
Can anyone please help me how to write this ternary operator inside the filter function in scala.
我同意我可以编写一个自定义函数来处理此问题,如@ Scala中的三元运算符
但是,我对为什么该语句出现编译错误感兴趣。
因为这是Java中的有效语句。
I agree that I can write a custom function to handle this as mentioned @ Ternary Operators in Scala However, I am interested in why there is compilation error for this statement. Because, this is valid statement in Java.
推荐答案
主要问题是Scala不支持三元运算符。你描述的。这是受Java支持的,但在Scala中是不需要的。
The main issue is that Scala does not support the ternary operator you described. That is supported Java but there's no need for it in Scala.
在Java中, if
statement 和三元运算符是后者是一个表达式,表示它是根据结果求值的,而 if
是(如我之前所建议的)a
In Java the main difference between the if
statement and the ternary operator is that the latter is an expression, meaning that it's evaluated to a result, while if
is (as I previously suggested) a statement that relies on side-effects within its scope to make things happen.
在Scala 中,如果
已经是一个表达式,则该语句依靠其范围内的副作用使事情发生。 ,因此不需要三元运算符。
In Scala if
is already an expression, hence there is no need for a ternary operator.
您的代码结构如下:
val filteredList = list.filter { l => if (pid == "") true else l.ProviderId.toUpperCase().contains(pid.toUpperCase()) }
如评论中所建议,您可以不依靠 if
来表达简单的布尔条件,从而进一步提高可读性。
As suggested in a comment you can further improve the readability by not relying on if
s to express simple boolean conditions.
val filteredList = list.filter { l => pid == "" || l.ProviderId.toUpperCase().contains(pid.toUpperCase())) }
此外,在在您的情况下, pid
似乎在列表本身之外,因此可以将其从过滤器
(具有列表
上的 O(n)复杂度可以为您节省一些周期:
Furthermore, in your case, pid
seems to be external to the list itself, so maybe pulling it out of the filter
(which has O(n) complexity on List
) can save you some cycles:
val filteredList = if (pid.isEmpty) list else list.filter(_.ProviderId.toUpperCase().contains(pid.toUpperCase()))
您似乎还想对两个字符串进行大小写敏感的相等性检查,在这种情况下,您可能会对使用模式
,并且在每个循环中都不将 pid
转换为大写:
It also looks like you are trying to make a case-insensive equality check on the two string, in which case you may be interested in using a Pattern
and not converting pid
to upper case at every loop:
val pidPattern = Pattern.compile(Pattern.quote(pid), Pattern.CASE_INSENSITIVE)
val filteredList = if (pid.isEmpty) list else list.filter(l => pidPattern.matcher(l.ProviderId).find)
这篇关于Scala程序中的三元运算符用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!