gpt4 book ai didi

scala - 如何在不分配给 val 的情况下使用隐式调用返回的函数

转载 作者:行者123 更新时间:2023-12-05 08:49:32 26 4
gpt4 key购买 nike

假设我有一个像这样的对象:

object MyObj {
def apply(args: List[String])(implicit v: Int): Unit => Int = (_: Unit) => args.length + v
}

如果我想要 MyObj.apply,我必须这样做:

implicit val v = 5
val myObj = MyObj(List("a", "b", "c"))
myObj()

但这感觉是多余的。我希望能够做的是:

implicit val v = 5
MyObj(List("a", "b", "c"))()

不幸的是,这似乎行不通。系统提示我缺少我的隐式参数,这是有道理的,但却是一个无赖。

有什么方法可以直接调用从 apply 方法返回的函数,而无需先将其赋值?

最佳答案

这是 scala 2.XX 中的一个已知问题,已在 dotty 中修复。

引用这张票的第三点:

Passing explicit arguments to implicit parameters is written like normal application. Thisclashes with elision of apply methods. For instance, if you have

def f(implicit x: C): A => Bthen f(a) would pass the argument a to the implicit parameter and one has to writef.apply(a) to apply f to a regular argument.

https://github.com/lampepfl/dotty/issues/1260

关于scala - 如何在不分配给 val 的情况下使用隐式调用返回的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63851866/

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