mis*_*tor 17
Scala中没有数据类型强制执行Boolean
.
所以... true
是真的,而且false
是假的.没有其他值可以用作布尔值.
它不能比这更简单.
我不知道为什么之前没有人回答这个问题。@Aaron 是对的,但他的回答超出了 OP 范围。
您可以通过隐式转换将所有值强制转换为布尔值,例如:
implicit def toBoolean(e: Int) = e != 0
implicit def toBoolean(e: String) = e != null && e != "false" && e != ""
...
Run Code Online (Sandbox Code Playgroud)
但你甚至可以拥有更好的东西。要使类型对于您自己的类型表现得像 javascript:
trait BooleanLike[T] {
def isTrue(e: T): Boolean
}
implicit object IntBooleanLike extends BooleanLike[Int] {
def isTrue(e: Int) = e != 0
}
implicit object StringBooleanLike extends BooleanLike[String] {
def isTrue(e: String) = e != null && e != ""
}
implicit class RichBooleanLike[T : BooleanLike](e: T) {
def ||[U >: T](other: =>U): U = if(implicitly[BooleanLike[T]].isTrue(e)) e else other
def &&(other: =>T): T = if(implicitly[BooleanLike[T]].isTrue(e)) other else e
}
Run Code Online (Sandbox Code Playgroud)
现在你可以在 REPL 中尝试一下,它真的变得像 Javascript 一样。
> 5 || 2
res0: Int = 5
> 0 || 2
res1: Int = 2
> 2 && 6
res1: Int = 6
> "" || "other string"
res2: String = "other string"
> val a: String = null; a || "other string"
a: String = null
res3: String = other string
Run Code Online (Sandbox Code Playgroud)
这就是我喜欢 Scala 的原因。
归档时间: |
|
查看次数: |
1357 次 |
最近记录: |