Skip to content

How do I use macro to create objects of any class?Look for help. #12590

Discussion options

You must be logged in to vote
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)
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@yankun1992
Comment options

Answer selected by nicolasstucki
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants