Scala奇怪的隐式拳击转换错误 [英] Scala strange implicit boxing conversion error

查看:114
本文介绍了Scala奇怪的隐式拳击转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我以下原因为何不起作用吗?

Can someone tell me why the following does not work?

object TestObject {
    def map(f: (Double, Double) => Double, x2: Array[Double]) = {
        val y = x2.zip( x2 )
        val z = y.map(f)
        z
    }
}

产生此错误:

type mismatch; found : (Double, Double) => Double required: ((Double, Double)) => ?

推荐答案

在此代码段中,f是一个带有两个Double参数并返回Double的函数. 您正在尝试通过传递类型为Tuple2[Double,Double]的单个参数来调用f. 您可以通过首先更改f的类型来解决此问题:

In this snippet, f is a function taking two Double parameters and returning a Double. You are attempting to call f by passing a single argument of type Tuple2[Double,Double]. You can fix this by changing the type of f in the first place:

object TestObject {
    def map(f: ((Double, Double)) => Double, x2: Array[Double]) = {
        val y = x2.zip( x2 )
        val z = y.map(f)
        z
    }
}

您也可以将其声明为f: Tuple2[Double, Double] => Double以便更清楚(这是完全等效的).

You could also declare it as f: Tuple2[Double, Double] => Double to be clearer (this is entirely equivalent).

相反,您可以这样更改通话:

Conversely, you could change your call like this:

object TestObject {
    def map(f: (Double, Double) => Double, x2: Array[Double]) = {
        val y = x2.zip( x2 )
        val z = y.map(f.tupled)
        z
    }
}

tupled自动将您的(Double, Double) => Double函数转换为Tuple2[Double, Double] => Double函数. 但是请记住,每次调用TestObject.map

tupled automagically transforms your (Double, Double) => Double function into a Tuple2[Double, Double] => Double function. Keep in mind however that the conversion will be done on each call to TestObject.map

这篇关于Scala奇怪的隐式拳击转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆