【发布时间】:2018-03-02 03:08:12
【问题描述】:
我正在尝试通过以下方式将 Scala 的 && 重写为 and(我喜欢 python,这就是我尝试这样做的原因):
def and(p1: () => Boolean, p2: () => Boolean): Boolean = p1() && p2()
但是,当我尝试使用它时,例如:
def and(p1: () => Boolean, p2: () => Boolean): Boolean = p1() && p2()
if ((l < h.length) and (h(l) > h(i)))
(我把def放在前面只是为了调试,以确保它不是可见性问题),我得到:
Error:(40, 26) value and is not a member of Boolean
if ((l < h.length) and (h(l) > h(i)))
这是怎么回事???
【问题讨论】:
-
如所示
and不是 Boolean 的成员,定义其第一个参数为() => Boolean不会使其成为Boolean类型的成员 -
@cchantep - 好点...所以我必须以某种方式编写
implicit以使and可与Boolean一起使用? -
通常隐式转换过于自动化,降低可读性
-
请记住,
and和&&具有不同的优先级。将一个更改为另一个可能会改变程序的含义。可能不是一个好主意。 -
@AlvaroCarrasco - 是的,我确实注意到优先级不一样。有什么方法可以在 Scala 中操纵运算符的优先级(我认为没有)?
标签: scala