假设我有一个像这样的对象:
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. This clashes with elision of apply methods. For instance, if you have
def f(implicit x: C): A => B then f(a) would pass the argument a to the implicit parameter and one has to write f.apply(a) to apply f to a regular argument.
https://github.com/lampepfl/dotty/issues/1260
https://stackoverflow.com/questions/63851866/