You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala 3宏无法找到作用域内的given/implicit实例

问题分析与修复

你的Scala 3宏无法找到对应的given实例,核心问题及修复方案如下:

关键问题点

  • 类型参数顺序不匹配:Person类定义type R = String、type M = Int,宏原逻辑尝试查找TR[String, Int],但你提供的given实例是TR[Int, String],类型参数顺序完全相反。
  • 类型成员获取不稳定:依赖declaredTypes.head/last获取类型成员,编译器返回的类型顺序不固定,容易导致错误匹配。
  • 错误提示笔误:报错信息中写了ReModel,实际目标类型是TR。
  • 类型边界处理不严谨:并非所有类型成员都会被包装在TypeBounds中,直接匹配会漏掉非约束类型定义。

修复后的宏代码

import scala.quoted.*

object TransformerMacro:
  inline def resolveTransformer[T] = ${ resolveTransformerImpl[T] }

  def resolveTransformerImpl[T: Type](using Quotes) =
    import quotes.reflect.*

    val tpe = TypeRepr.of[T]

    // 根据类型名称精确查找R和M类型成员
    def findTypeMember(name: String): Option[TypeRepr] =
      tpe.typeSymbol.declaredTypes
        .find(_.name == name)
        .map(tpe.memberType)

    (findTypeMember("R"), findTypeMember("M")) match
      case (Some(rType), Some(mType)) =>
        (rType.asType, mType.asType) match
          case ('[r], '[m]) =>
            val rtn = Type.show[r]
            val mtn = Type.show[m]
            // 调整类型参数顺序以匹配现有given实例
            Expr.summon[TR[m, r]] match
              case Some(instance) =>
                report.info(s"找到given实例: TR[$mtn, $rtn] $instance")
                '{Some($instance)}
              case None =>
                report.error(s"未找到对应类型的given实例: TR[$mtn, $rtn]")
                '{None}
      case _ =>
        report.error("目标类型中未找到R或M类型成员")
        '{None}

配套调整说明

如果要保留你原有的TR[Int, String] given实例,宏中Expr.summon的类型参数需改为TR[m, r](对应TR[M, R])。若需要匹配TR[R, M],则修改given实例的类型参数为TR[String, Int]即可。


执行结果

修复后运行驱动代码:

def main(args: Array[String]): Unit =
  val resolved = TransformerMacro.resolveTransformer[Person]
  println(resolved)

会输出类似:Some(TR$strToInt@...)的结果。

内容的提问来源于stack exchange,提问作者Raman Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:37:11