无法在 Scala 3 中执行上下文函数的扩展方法

问题描述 投票:0回答:1

我在 Scala 3 中定义了上下文函数的扩展方法:

object Scope {
  extension [E, A](a: List[E] ?=> A) def extFoo: A = foo(a)
  
  private def foo[E, A](a: List[E] ?=> A) = {
    given s: List[E] = List.empty
    println(a)
    a
  }
}

但是,当我尝试使用它时,编译器会抱怨。以下

@main

@main def main(): Unit = {
  val i: List[String] ?=> Int = 1
  import Scope.extFoo
  i.extFoo
}

产生此错误:

No given instance of type List[String] was found for parameter of (List[String]) ?=> Int
  i.extFoo

如果我使用替代语法

extFoo(i)
调用扩展方法,一切都会正常工作。

这是预期的行为吗?

scala implicit scala-3
1个回答
0
投票

i.extFoo
中,无法编译的是
i
本身。
i
在范围内查找隐式
List[String]
,但没有找到这样的隐式。

这与文档一致

given ec: ExecutionContext = ...

def f(x: Int): ExecutionContext ?=> Int = ...

f(2)(using ec)   // explicit argument
f(2)             // argument is inferred

https://docs.scala-lang.org/scala3/reference/contextual/context-functions.html

.extFoo
尝试应用于此类应用的结果,而不是原始隐式函数。

....extFoo
是否可以解析取决于范围内是否存在扩展方法,但
.extFoo
无法修复
...
的编译。

https://scala-lang.org/files/archive/spec/3.4/07-implicits.html#views

如果您的意思是

.extFoo
应该应用于原始隐式函数,那么您可以使用隐式 lambda

来指定它
val i: List[String] ?=> Int = 1
import Scope.extFoo
((_: List[String]) ?=> i).extFoo // compiles
© www.soinside.com 2019 - 2024. All rights reserved.