gpt4 book ai didi

scala - 按名称调用函数体的隧道隐式参数

转载 作者:行者123 更新时间:2023-12-02 04:46:06 25 4
gpt4 key购买 nike

考虑以下代码片段:

object Example {

def run(f: => Unit): Unit = {
implicit val i = 1

f
}

def caller(): Unit =
run {
todo
}

def todo(implicit i: Int): Unit =
println(i)
}

当前未编译并显示以下消息:

Error:(14, 13) could not find implicit value for parameter i: Int
todo
^

我的问题是,是否可以使隐式参数可用于按名称调用的函数体?

编辑我尝试按照 Alexey Romanov

的建议让它与宏实现一起工作
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context

object Macros {

def run(f: => Unit): Unit = macro runImpl

def runImpl(c : Context)(f: c.Tree) = {
import c.universe._
q"""{
implicit val i: Int = 3
$f
}"""
}
}

object Example extends App {

Macros.run {
todo
}

def todo(implicit i: Int): Unit =
println(i)

}

调试宏我可以看到它被正确扩展成

{
implicit val i: Int = 3
Example.this.todo
}

不幸的是,它没有编译好,同样的错误是找不到隐含的。

深入研究问题我发现了讨论 here和 jira 问题 https://issues.scala-lang.org/browse/SI-5774

所以问题是一样的:在这种情况下是否可以将隐式隧道隐式传输到 todo 函数中?

最佳答案

简单地说-不。 implicit 要求从代码中可以清楚地看出发生了什么。如果您希望将任何内容隐式传递给函数,它必须具有 implicit 参数,这不是您的 f 函数的情况。

这是与implicit 相关的重要智慧来源: http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html

关于scala - 按名称调用函数体的隧道隐式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682342/

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