在scala 2或3中,是否可以在运行时调试隐式解析过程?

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

在scala语言中,隐式解析通常在编译时完成,有时会抛出混淆错误信息,此类错误的一个著名示例是当无形状的泛型抛出错误信息时,例如:

error: could not find implicit value for parameter encoder: CsvEncoder[Foo]

((有关详细信息,请参见https://books.underscore.io/shapeless-guide/shapeless-guide.html

此问题的解决方案是在运行时中运行隐式分辨率算法(应该是内部图查询算法),这至少具有两个好处:

  • 调试工具可用于逐步重现解决过程,因此,即使错误信息和文档不完整,也很容易发现错误。

  • 在许多情况下,类型信息可能无法在编译时确定(例如,类型取决于控制流)。如果不能将隐式转换延迟到运行时阶段,则定义隐式转换的许多好处将被取消。

所以我的问题是,此功能是否存在于Scala 2.x或Dotty中?还是在路线图上?

非常感谢您的意见。

scala implicit scala-reflect scalameta dotty
1个回答
0
投票

您可以在编译时调试隐式:

  1. 打开-Xlog-implicits

  2. 尝试手动解析隐式(也许还指定类型参数)并查看编译错误

    implicitly[...](...manually...)
    
  3. 使用scala.reflect

    println(reify { implicitly[...] }.tree)
    
  4. 使用IDE功能显示隐式对象

  5. 将宏与编译器内部一起使用,您可以调试隐式分辨率

    Is there a type-class that checks for existence of at least one implicit of a type?

    create an ambiguous low priority implicit

    Using the "Prolog in Scala" to find available type class instances

    Finding the second matching implicit

    https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/package.scala#L119-L168

如果您正在开发类型类,请不要忘记使用注释@implicitNotFound@implicitAmbiguous

© www.soinside.com 2019 - 2024. All rights reserved.