How to run the Defn generated by the scalameta

92 Views Asked by At

I am playing with Scalameta. this is my 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")

In my MacroProject. I have the following code

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
   }
}

And now in my main Project I write

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

My hope was that I will be able to execute the method which was generated by my macro.

Edit: I also tried

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"
      }
   }
}
0

There are 0 best solutions below