假设我有一个简单的数字列表,例如:
val numbers = List.range(1,10)
Run Code Online (Sandbox Code Playgroud)
我想过滤它,使用&运算符 - 似乎正在运行的最短解决方案是:
numbers.filter( x => ( x & 1 ) == 0 )
Run Code Online (Sandbox Code Playgroud)
但是我不确定为什么我需要()这里,或者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 )
Run Code Online (Sandbox Code Playgroud)
另一个令人困惑的部分是,%运算符工作正常.
// --- all good
numbers.filter( _ % 2 == 0 )
// --- error
//
// type mismatch;
// found : Int
// required: Boolean
// numbers.filter( _ & 1 )
//
numbers.filter( _ & 1 )
Run Code Online (Sandbox Code Playgroud)
那么为什么"x%2 == 0"会起作用,而"x&1 == 0"会失败,因为它们会产生类似的结果(我认为).如果我正确理解错误 - "x&1"的结果是整数.我认为它与&运营商有关,但无法弄清楚我在哪里查找它.
斯卡拉:2.10
在此先感谢您的帮助和任何建议.
运营商%和&有不同的侧重点.因此,_ & 1 == 0尝试将1与0进行比较,然后&对布尔结果执行.
增加优先顺序:
Run Code Online (Sandbox Code Playgroud)(all letters) | ^ & = ! < > : + - * / % (all other special characters)