1

I have a method that uses foldLeft in Scala.

def bitSetToByte(b:collection.BitSet, sh:Int=0) = 
  ((0 /: b) {(acc, input) => acc + (1 << (input - sh))}).toByte

The method has two parameters for the anonymous function, so I replaced it with _ by removing formal arguments.

def bitSetToByte(b:collection.BitSet, sh:Int=0) = ((0 /: b) {(_ + (1 << (_ - sh))}).toByte

The issue is that I have type mismatch error message.

enter image description here

What might be wrong?

prosseek
  • 182,215
  • 215
  • 566
  • 871

2 Answers2

4

When interpreting _, the compiler assumes that the anonymous function that the _ corresponds to is enclosed in the nearest set of parentheses (except for (_)). Basically, the compiler interpreted (_ - sh) to be (x => x - sh), then complained because you were passing a function to << when it expected an Int.

wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
0

Frist, you messed up with parentheses. I guess you meant something like (also i removed toByte for brievity)

def bitSetToByte(b:collection.BitSet, sh:Int) = 
  (0 /: b) { (_ + (1 << (_ - sh))) }

Second, typer is your firend, you can find out how your code looks after the typer phase of compiler by running scala interpreter with -Xprint:typer flag

def bitSetToByte(b: scala.collection.BitSet, sh: Int): Int = {
  <synthetic> <artifact> val x$1: Int = 0;
  b./:[Int](x$1)(((<x$2: error>: <error>) => <x$2: error>.<$plus: error>(1.$less$less(((x$3) => x$3.$minus(sh))))))
}

lambda expression can be simplified to

{ x2 => x2 + (1 << (x3 => x3 - sh)) }

which is not what you wanted

4e6
  • 10,696
  • 4
  • 52
  • 62