假设我有一个简单的数字列表,例如:
val numbers = List.range(1,10)
我想使用&运算符对其进行过滤-似乎可行的最短解决方案是:
numbers.filter( x => ( x & 1 ) == 0 )
但是我不确定为什么我需要在这里()或x,但是似乎给了我以下错误(这似乎是&的问题,但是我不确定如何在文档中查找它) :
//
// 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 )
那么为什么“ x%2 == 0”会起作用,而“ x&1 == 0”会失败,因为它们会产生相似的结果(我认为)。如果我正确理解错误,则“ x&1”的结果为整数。而且我认为这与&运算符有关,但无法弄清楚我会在哪里查找。
斯卡拉(Scala):2.10
在此先感谢您的帮助和任何建议。
运营商%
和&
有不同的优先级。因此,_ & 1 == 0
尝试将1与0进行比较,然后&
对布尔结果进行运算。
优先顺序从高到低:
(all letters) | ^ & = ! < > : + - * / % (all other special characters)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句