gpt4 book ai didi

Scala,Currying 多参数组方法,包括隐式参数?

转载 作者:行者123 更新时间:2023-12-04 11:41:53 25 4
gpt4 key购买 nike

在发现 currying multi parameter-groups method is possible ,我试图获得一个需要隐式参数的部分应用函数。

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

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 的范围内使用它。

最佳答案

那是因为您在范围内没有隐式 Int 。看:

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>

编译器将隐式替换为实际值。如果您对方法进行 curry,则结果是一个函数,并且函数不能有隐式参数,因此编译器必须在您对方法进行 curry 时插入该值。

编辑:

对于您的用例,为什么不尝试以下方法:
object Foo {
def partialSum(implicit x: Int) = sum(3)(x)
}

关于Scala,Currying 多参数组方法,包括隐式参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10881340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com