2016-08-18 160 views
4

按位與運算的假設我有一個數字的簡單列表,像: 使用過濾器

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」 的工作, 「×& 1 == 0」 失敗,因爲它們產生類似的結果(我認爲)。如果我正確理解錯誤 - 「x & 1」的結果是一個整數。我認爲這與&運營商有關,但無法弄清楚我在哪裏查找它。

斯卡拉:2.10

預先感謝您的幫助和任何建議。

+0

由於操作者的優先級; '=='比'&'具有更高的優先權,所以'x&1 == 0'表示'x&(1 == 0)'而不是'(x&1)== 0'。 – Jesper

回答

6

運營商%&有不同的優先級。因此_ & 1 == 0會嘗試將1與0進行比較,然後對布爾結果執行&

參見Scala Reference - 6.12.3 Infix Operations

優先增加的順序:

(all letters) 
| 
^ 
& 
= ! 
< > 
: 
+ - 
*/% 
(all other special characters)