我在玩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"
}
}
}