Scala中的三元运算符 [英] Ternary Operators in Scala
本文介绍了Scala中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想简化这个:
var countA: Int = 0
var countB: Int = 0
if (validItem) {
if (region.equalsIgnoreCase( "US" )) {
if (itemList > 0) {
countB = 1
} else {
countA = 1
}
} else {
countB = 1
}
} else {
countA = 1
}
如何在scala中使用三元运算符。
How do I use ternary operator in scala.
推荐答案
对于新手来说这可能有点令人困惑,但你可以在<$ c $上附加一个三元方法c> Boolean 类似的。
This might be a bit confusing for a "newbie", but you could attach a ternary method to the Boolean
class like so.
implicit class Ternary[T](condition: Boolean) {
def ??(a: => T, b: => T): T = if (condition) a else b
}
用法:
(4 == 4)??("yes","no") // res0: String = yes
("abc".length < 2).??(1,0) // res1: Int = 0
List('c').isEmpty.??('X','+') // res2: Char = +
这篇关于Scala中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文