使用Scala中的foldLeft方法键入不匹配错误

时间:2014-06-04 18:42:40

标签: scala types foldleft

我有一个在Scala中使用foldLeft的方法。

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

该方法有两个匿名函数参数,所以我用_删除了正式参数替换它。

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

问题是我有类型不匹配错误消息。

enter image description here

可能出现什么问题?

2 个答案:

答案 0 :(得分:4)

在解释_时,编译器假定_对应的匿名函数包含在最近的括号集中((_)除外)。基本上,编译器将(_ - sh)解释为(x => x - sh),然后抱怨,因为您在预期<<时将函数传递给Int

答案 1 :(得分:0)

Frist,你搞砸了括号。我想你的意思是(我也为了简洁而删除了toByte

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

其次,typer是你的火,你可以通过运行带有-Xprint:typer标志的scala解释器来了解你的代码在编译器的typer阶段之后的样子

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表达式可以简化为

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

这不是你想要的