Dmitry F Dmitry F - 3 months ago 9
Scala Question

Use of a bitwise AND operator in filter

Assuming I have a simple list of numbers, something like:


val numbers = List.range(1,10)


And I want to filter it, using & operator - the shortest solution that seems to be working is:


numbers.filter( x => ( x & 1 ) == 0 )


However I'm not sure why do I need () here, or x, but it seems to give me a following error otherwise (which seems that & is an issue, but I'm not sure how to look it up in 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 )


Also another confusing part, is that % operator works just fine.


// --- all good
numbers.filter( _ % 2 == 0 )

// --- error
//
// type mismatch;
// found : Int
// required: Boolean
// numbers.filter( _ & 1 )
//
numbers.filter( _ & 1 )


So why would "x % 2 == 0" work, and "x & 1 == 0" fail, because they produce similar results (I think). If I understand an error properly - the result of "x & 1" is an integer. And I assume it's something to do with & operator, but can't figure out where would I look it up.

Scala: 2.10

Thanks in advance for your help and any suggestions.

Answer

Operators % and & has different priorities. So _ & 1 == 0 tries to compare one to zero and then perform & on boolean result.

See Scala Reference - 6.12.3 Infix Operations :

increasing order of precedence:

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