真实和虚假的价值观

Ral*_*ing 4 scala

在Scala中确定对象是否真实/虚假的规则是什么?我发现许多其他语言,如Ruby,JavaScript等,但似乎无法找到Scala的权威列表.

mis*_*tor 17

Scala中没有数据类型强制执行Boolean.

所以... true是真的,而且false是假的.没有其他值可以用作布尔值.

它不能比这更简单.

  • Wellll,这是Scala,你可以自己强迫:`implicit def intsAreBooleanHaHaHa(i:Int)= if(i == 0)false else true`.不是说这是个好主意. (10认同)

Mik*_*yer 5

我不知道为什么之前没有人回答这个问题。@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 的原因。

  • 这是我见过的最令人愉快的邪恶事情之一。 (2认同)