假设我有一个简单的数字列表,例如:
val numbers = List.range(1,10)
我想过滤它,使用&运算符 - 似乎正在运行的最短解决方案是:
numbers.filter( x => ( x & 1 ) == 0 )
但是我不确定为什么我需要()这里或x,但它似乎给了我一个跟随错误(这似乎&是一个问题,但我不确定如何在docs中查找:
//
// overloaded method value & with alternatives:
// (x: Long)Long <and>
// (x: Int)Int <and>
// (x: Char)Int <and>
// (x: Short)Int <and>
// (x: Byte)Int
// cannot be applied to (Boolean)
// numbers.filter( _ & 1 == 0 )
//
numbers.filter( _ & 1 == 0 )
另一个令人困惑的部分是,%运算符工作得很好。
// --- all good
numbers.filter( _ % 2 == 0 )
// --- error
//
// type mismatch;
// found : Int
// required: Boolean
// numbers.filter( _ & 1 )
//
numbers.filter( _ & 1 )
那么为什么&#34; x%2 == 0&#34;工作,&#34; x&amp; 1 == 0&#34;失败,因为他们产生了类似的结果(我认为)。如果我理解错误 - &#34; x&amp; 1&#34;是一个整数。而且我认为这与&amp; amp;运营商,但无法弄清楚我会在哪里查找。
斯卡拉:2.10
提前感谢您的帮助和任何建议。
答案 0 :(得分:6)
运营商%
和&
有不同的优先级。因此_ & 1 == 0
尝试将1与0进行比较,然后对布尔结果执行&
。
请参阅Scala Reference - 6.12.3 Infix Operations:
增加优先顺序:
(all letters) | ^ & = ! < > : + - * / % (all other special characters)