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

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

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/

相关文章:

python - 为什么在 Pi 的整数倍处 torch.sin() 和 numpy.sin() 的

f# - 在 F# 中添加两个元组

javascript - 悬停时高效的 JS 事件监听器

python - 从数据框中删除列中以 "@"开头的单词

python - Python 中的 Marching Square 算法

python - 如何将带有元组键的 python 字典转换为 pandas 多索引数据框?

java - 阵列旋转 TLE(超出时间限制)

amazon-web-services - 服务器端加密与客户端加密 - Amazon S3

java - Hibernate: OneToOne: 同一类型的两个字段

python - 使用 Pandas 和 R 将序列号连接到组中的每一行