gpt4 book ai didi

scala - Scala 2.12 中的隐式 ExecutionContext 优先级

转载 作者:行者123 更新时间:2023-12-03 10:12:40 31 4
gpt4 key购买 nike

在 Scala 2.12 中导入 global执行上下文然后在范围中定义另一个隐式执行上下文会导致模糊的隐式,而在 2.11 中它工作得很好。

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global

class A(implicit ec: ExecutionContext) {
x = implicitly[ExecutionContext]
}

编译器报错:
error: ambiguous implicit values:
both lazy value global in object Implicits of type => scala.concurrent.ExecutionContext
and value ec in class A of type scala.concurrent.ExecutionContext
match expected type scala.concurrent.ExecutionContext
val x = implicitly[ExecutionContext]
^

这是什么原因以及如何在代码中解决它?

最佳答案

该规范将重载决议视为消除类成员选择的歧义。但是隐式解析使用静态重载解析在不是成员的引用之间进行选择。

可以说,以下是对规范的误解,因为 zzz在派生自 X 的类中定义多达 yyy是:

$ scala
Welcome to Scala 2.12.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> import concurrent._, ExecutionContext.global
import concurrent._
import ExecutionContext.global

scala> trait X { implicit val xxx: ExecutionContext = global }
defined trait X

scala> class Y extends X { implicit val yyy: ExecutionContext = global ; def f = implicitly[ExecutionContext] }
defined class Y

scala> class Z extends X { def f(implicit zzz: ExecutionContext) = implicitly[ExecutionContext] }
<console>:16: error: ambiguous implicit values:
both value xxx in trait X of type => scala.concurrent.ExecutionContext
and value zzz of type scala.concurrent.ExecutionContext
match expected type scala.concurrent.ExecutionContext
class Z extends X { def f(implicit zzz: ExecutionContext) = implicitly[ExecutionContext] }
^

目前,您必须依靠命名来隐藏封闭范围内的隐式:
scala> class Z extends X { def f(implicit xxx: ExecutionContext) = implicitly[ExecutionContext] }
defined class Z

或者,
scala> :pa
// Entering paste mode (ctrl-D to finish)

package object p { import concurrent._ ; implicit val xxx: ExecutionContext = ExecutionContext.global }
package p { import concurrent._ ;
class P { def f(implicit xxx: ExecutionContext) = implicitly[ExecutionContext]
def g = implicitly[ExecutionContext] }
}

// Exiting paste mode, now interpreting.


scala>

关于scala - Scala 2.12 中的隐式 ExecutionContext 优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40442717/

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