首页 > 解决方案 > Scala 2.13.1 无法使用宏

问题描述

我无法在 scala中使用2.13.1

我不断收到以下错误:

object blackbox is not a member of package scala.reflect.macros

这显然不是真的,因为 scala 2.13.1 实际上有这些黑盒。我做错了什么?

你好.scala

package example.core

import example.macros.MacroLibrary

object Hello extends App {
  MacroLibrary.hello()
}

宏库.scala

package example.macros

// This line throws errors
import scala.reflect.macros.blackbox.Context
import scala.reflect.macros.blackbox

object MacroLibrary {
  def hello_impl(c: blackbox.Context)(): c.Expr[Unit] = {
    import c.universe._
    c.Expr(q"""println("Hello World")""")
  }

  def hello(): Unit = macro hello_impl
}

构建.sbt

scalaVersion := "2.13.1"

错误

object blackbox is not a member of package scala.reflect.macros

标签: scalamacros

解决方案


它们不在标准库中,而是在单独scala-reflect的 中,需要将其作为依赖项添加到build.sbt

libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value

您可以从左上角有“Scala Reflection Library”的Context文档中看到。


推荐阅读