How do I use macro to create objects of any class?Look for help. #12590
Answered
by
giiita
yankun1992
asked this question in
Metaprogramming
Replies: 1 comment 1 reply
-
import scala.quoted._
object Macro {
def createImpl[T: Type](expr: Expr[Seq[Any]])(using q: Quotes): Expr[T] = {
import q.reflect._
expr match {
case Varargs(params) =>
Select.overloaded(New(q.reflect.TypeTree.of[T]), "<init>", Nil, params.toList.map(_.asTerm)).asExprOf[T]
}
}
} case class Hello(value: String)
case class World(id: Int, value: String)
inline def createObject[T](inline args: Any*): T = ${ Macro.createImpl[T]('args) }
@main
def test: Unit = {
val world: World = createObject[World](1, "bbb")
println(world)
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
nicolasstucki
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Beta Was this translation helpful? Give feedback.
All reactions