Using the bitwise AND operator in a filter

Assuming I have a simple list of numbers, for example:

val numbers = List.range(1,10)

And I want to filter it using the operator, too - the shortest solution that seems to work:

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

However, I'm not sure why I need (or here), or x, but it seems to give me the following error otherwise (it seems like a problem, but I'm not sure how to look for it in the 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 the other confusing part is that the% 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 does “x% 2 == 0” work, but “x and 1 == 0” fail because they give similar results (I think). If I understand the error correctly, the result of "x and 1" is an integer. And I suppose this has something to do with the operator, but cannot figure out where I would look for it.

Scala: 2.10

.

+4
1

% & . , _ & 1 == 0 , & .

. Scala - 6.12.3 Infix:

:

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

Source: https://habr.com/ru/post/1651630/


All Articles