Scala,对包括隐式参数的多参数组方法进行柯里化? [英] Scala, Currying on multi parameter-group method including implicit params?

查看:40
本文介绍了Scala,对包括隐式参数的多参数组方法进行柯里化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发现柯里化多参数组方法是可能的之后,我试图获得一个部分应用的函数需要隐式参数.

After having discovered that currying multi parameter-groups method is possible, I am trying to get a partially applied function which requires implicit parameters.

似乎不可能这样做.如果不是,你能解释一下为什么吗?

It seams not possible to do so. If not could you explain me why ?

scala> def sum(a: Int)(implicit b: Int): Int = { a+b }
sum: (a: Int)(implicit b: Int)Int

scala> sum(3)(4)
res12: Int = 7

scala> val partFunc2 = sum _
<console>:8: error: could not find implicit value for parameter b: Int
       val partFunc2 = sum _
                       ^

我使用一个单例对象来创建这个部分应用的函数,我想在定义了隐式 int 的范围内使用它.

I use a singleton object to create this partially applied function and I want to use it in a scope where the implicit int is defined.

推荐答案

那是因为您在作用域中没有隐式 Int.见:

That is because you don't have an implicit Int in scope. See:

scala> def foo(x: Int)(implicit y: Int) = x + y
foo: (x: Int)(implicit y: Int)Int

scala> foo _
<console>:9: error: could not find implicit value for parameter y: Int
              foo _
              ^

scala> implicit val b = 2
b: Int = 2

scala> foo _
res1: Int => Int = <function1>

隐式被编译器替换为实际值.如果你对方法进行柯里化,结果是一个函数,函数不能有隐式参数,所以编译器必须在你柯里化方法时插入值.

The implicit gets replaced with a real value by the compiler. If you curry the method the result is a function and functions can't have implicit parameters, so the compiler has to insert the value at the time you curry the method.

对于您的用例,为什么不尝试以下操作:

For your use case, why don't you try something like:

object Foo {
  def partialSum(implicit x: Int) = sum(3)(x)
}

这篇关于Scala,对包括隐式参数的多参数组方法进行柯里化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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