如何通过 Scala 反射获得可用的隐式? [英] How to get implicits available via Scala reflection?

查看:52
本文介绍了如何通过 Scala 反射获得可用的隐式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个解析器生成器来创建 Scala 案例类.举个例子:

I'm writing a parser-generator that creates Scala case classes. Take this example:

case class Foo(
   name : String,
   age : Int
)(implicit other:Int){}

当我想实现一个 Foo 实例时,我的解析器生成器知道所有 3 个成员,包括隐含的其他".我有数据来填充 name &年龄.

When I want to materialize a Foo instance my parser-generator has knowledge of all 3 members, including the implicit 'other'. I have the data to populate name & age.

使用 Scala 反射,如何在创建对象时检查隐式环境"以找到合适的其他"值?

Using Scala reflection, how can I inspect the "implicit environment" when the object will be created to find an appropriate value for 'other'?

推荐答案

您不能:可用的隐式依赖于导入、局部变量等,而这些在运行时根本不可用.如果您可以使用宏,则可以使用 c.inferImplicitValue 方法.请参阅 Scala 宏 - 使用 `c.prefix` 推断隐式值https://groups.google.com/forum/#!topic/scala-language/rqNZMBuJLtE 一些例子,但如果你需要这条路线的帮助,我建议提出一个单独的问题.

You can't: the implicits available depend on things like imports, local variables, etc. which aren't available at runtime at all. If you can get away with a macro, there is the c.inferImplicitValue method. See Scala macro - Infer implicit value using `c.prefix` or https://groups.google.com/forum/#!topic/scala-language/rqNZMBuJLtE for some examples, but if you want help with this route I advise asking a separate question.

这篇关于如何通过 Scala 反射获得可用的隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆