scala隐式类方法类型不匹配的reduce与非隐式方法的函数currying

Mic*_*ser 3 scala function currying implicits

问题:

关于隐式类的东西,混淆reduce().在隐式类内部时,编译器会在reduce()第二个参数上抱怨.但是当相同的代码在非隐式方法中时,它编译并正常工作.

我对隐含类缺少什么?

码:

object ImpliCurri {
    implicit class MySeq[Int](val l: Seq[Int]) {
        //not compiling
        final def mapSum(f:Int=>Int):Int = {
            l.map(x=>f(x)).reduce(_+_)
       //compile error on reduce: Type mismatch. Expected String, fount Int
        }
    }

    // works fine
    def mySum(l:Seq[Int], f:Int=>Int):Int = {
        l.map(x=>f(x)).reduce(_+_)
        // compiles and works no issues
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*jac 5

你需要摆脱类型参数Int.Int在隐式类的情况下实际上Int不是类型,而是它是一个自由类型参数,它隐藏了名称Int.

产生神秘编译错误的原因是编译器正在推断Anylambda中_ + _的类型(因为类型参数可能是任何东西),并假设+它将来自toStringon类型Any.如果在类声明中替换IntT,则会看到错误是相同的.

这将有效:

implicit class MySeq(val l: Seq[Int]) {
    final def mapSum(f: Int => Int): Int = {
        l.map(x => f(x)).reduce(_ + _)
    }
 }
Run Code Online (Sandbox Code Playgroud)