gpt4 book ai didi

scala - 如何运行官方反射示例

转载 作者:行者123 更新时间:2023-12-02 09:24:36 27 4
gpt4 key购买 nike

我在使用官方代码尝试一些反射时遇到问题[ https://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html]

我使用sbt创建了2个包,app包依赖于宏包,我将宏代码放在宏包中并将代码导入到app包中调用它,但效果不佳。

import scala.reflect.macros.Context

case class Location(filename: String, line: Int, column: Int)

object Macros {
def currentLocation: Location = macro impl

def impl(c: Context): c.Expr[Location] = {
import c.universe._
val pos = c.macroApplication.pos
val clsLocation = c.mirror.staticModule("Location") // get symbol of "Location" object
c.Expr(Apply(Ident(clsLocation), List(Literal(Constant(pos.source.path)), Literal(Constant(pos.line)), Literal(Constant(pos.column)))))
}
}

[错误] scala.ScalaReflectionException:找不到对象位置。[错误] 在 scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:168)[错误] 在 scala.reflect.internal.Mirrors$RootsBase.staticModule(Mirrors.scala:29)[错误] 在 sg.bigo.Macros$.impl(Macros.scala:61)[错误] currentLocation.column

最佳答案

编译以下项目

App.scala

import Macros.currentLocation

object App {
def main(args: Array[String]): Unit = {
println(
currentLocation //Location(/media/data/Projects/macrosdemo213/core/src/main/scala/App.scala,6,7)
)
}
}

宏.scala

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

case class Location(filename: String, line: Int, column: Int)

object Macros {
def currentLocation: Location = macro impl

def impl(c: blackbox.Context): c.Tree = {
import c.universe._
val pos = c.macroApplication.pos
val clsLocation = c.mirror.staticModule("Location")
q"$clsLocation(${pos.source.path}, ${pos.line}, ${pos.column})"
}
}

build.sbt

name := "macrosdemo213"

lazy val commonSettings = Seq(
scalaVersion := "2.13.0",
organization := "com.example",
version := "1.0.0",
)


lazy val macros: Project = (project in file("macros")).settings(
commonSettings,
libraryDependencies ++= Seq(
scalaOrganization.value % "scala-reflect" % scalaVersion.value,
)
)

lazy val core: Project = (project in file("core")).aggregate(macros).dependsOn(macros).settings(
commonSettings
)

build.properties

sbt.version = 1.2.8

项目结构

enter image description here

关于scala - 如何运行官方反射示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642599/

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