3

我在玩 Scalameta。这是我的 build.sbt

lazy val commonSettings = Seq(
   scalaVersion := "2.12.3"
)
lazy val macroProject = (project in file("MacroProject")).settings(
   commonSettings,
   name := "MacroProject",
   libraryDependencies ++= Seq("org.scalameta" % "scalameta_2.12" % "2.0.1")
)

lazy val myProject = (project in file(".")).settings(
   commonSettings,
   name := "MyProject"
).dependsOn(macroProject)

mainClass in run := Some("com.abhi.HelloWorld")

在我的宏项目中。我有以下代码

import scala.meta._
import org.scalameta.logger

object MyMacros {
   def foo(a: Any, b: String) = {
      val result = q"def foo() : b = a.asInstanceOf[b]"
      result
   }
}

现在在我的主要项目中我写

import com.abhi.MyMacros
MyMacros.foo("1", "Int").apply()

我希望我能够执行由我的宏生成的方法。

编辑:我也试过

object MyMacros {
   def foo(a: Any, b: String) = {
      val typeB = b.parse[Type]
      typeB match {
         case Success(t) => q"def foo() : $t = a.asInstanceOf[$t]"
         case _ => q"def foo() = Unit"
      }
   }
}
4

0 回答 0