简体   繁体   English

Scala中的foldLeft方法导致类型不匹配错误

[英]Type mismatch error with foldLeft method in Scala

I have a method that uses foldLeft in Scala. 我有一个在Scala中使用foldLeft的方法。

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. 问题是我有类型不匹配错误消息。

在此处输入图片说明

What might be wrong? 可能是什么问题?

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 . 基本上,编译器将(_ - sh)解释为(x => x - sh) ,然后抱怨,因为当您期望将Int传递给<<时,您要将函数传递给<<

Frist, you messed up with parentheses. 第一拳,你把括号弄乱了。 I guess you meant something like (also i removed toByte for brievity) 我猜你的意思是这样(我也删除toByte为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 其次,typer是您的朋友,您可以使用-Xprint:typer标志运行scala解释器,从而了解代码在编译器的-Xprint: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 expression can be simplified to lambda表达式可以简化为

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

which is not what you wanted 那不是你想要的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM