0
votes

I am new to scala but I am having the problem with the following code:

var c:Int = 0
var j:Int = 0

for( c <- 0 to 100){
  for( j <- 0 to 100){

   /* Check if jth bit in c is set,
    if( (c & (1<<j)) )  // this line is the line where i get the error
    xs :+ (ys(j))   // this is copying element j from list ys to list xs     
  }
}

The error I get is: type mismatch; found : Int required: Boolean

the code (c & (1<<j)) should be shifting 1 left j bits and then bitwise anding the result to the int in the variable c to get a boolean result.

It is entirely possible that I am doing something wrong.. I have been learning Scala fro 3 days and I am very rusty on my java.

Any help would be appreicated

2

2 Answers

2
votes

Bitwise operations in Scala (in fact in any language) return a result of type Int, your if expression requires a type of Boolean. Scala doesn't treat Boolean values like C, where you code would work fine.

You can make your expression return a Boolean by testing explicitly for 1:

if((c & (1 << j)) != 0)
1
votes

Unlike in C (or C++), Scala's if statement (just like Java) only accepts a Boolean expression, and there is no implicit type promotion from integral types to Boolean. So you need to be explicit about what you want, and replace if( (c & (1<<j)) ) with if( (c & (1<<j)) != 0)