【发布时间】:2013-02-11 22:43:57
【问题描述】:
我喜欢可以使用布尔运算符编写的简洁代码,而不是像 Lisp、Python 或 JavaScript 这样的(通常是动态的)语言中的条件语句,就像典型的那样:
x = someString or "default string"
对
if someString:
x = someString
else:
x = "default string"
在 Scala 中,我曾想过这样的事情:
object Helpers {
case class NonBooleanLogic[A](x: A) {
// I could overload the default && and ||
// but I think new operators are less 'surprise prone'
def |||(y: => A)(implicit booleanConversion: A => Boolean) = if (x) x else y
def &&&(y: => A)(implicit booleanConversion: A => Boolean) = if (!x) x else y
}
implicit def num2bool(n : Int) = n != 0
implicit def seq2bool(s : Seq[Any]) = !s.isEmpty
implicit def any2bool(x : Any) = x != null
implicit def asNonBoolean[T](x: T) = NonBooleanLogic(x)
}
object SandBox {
// some tests cases...
1 ||| 2 //> res2: Int = 1
val x : String = null //> x : String = null
x ||| "hello" //> res3: String = hello
//works promoting 2 to Float
1.0 &&& 2 //> res4: Double = 2.0
//this doesn't work :(
1 &&& 2.0
}
但出现了两个问题:
- 如何使其适用于具有共同祖先的类型而不恢复为
Any类型? - 这太酷了,以前一定有人做过,可能是在一个文档更好、经过测试和全面的库中。在哪里可以找到它?
【问题讨论】:
-
顺便说一句,这更惯用:
val x = if (someString != null && someString.size() > 0) someString else "default string"; -
它应该是 JavaScript,而不是 Scala
-
你的第二个sn-p可以写成
val x = Option(someString).filterNot(_.isEmpty).getOrElse("default string")或val x = if(someString != null && someString.size() > 0) someString else "default string" -
我想我会将 sn-ps 更改为 Python,以免一遍又一遍地回答相同的问题 xD
标签: scala boolean type-safety