Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9122541
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T06:07:42+00:00 2026-06-17T06:07:42+00:00

I would like to program a Scala macro that takes an instance of a

  • 0

I would like to program a Scala macro that takes an instance of a case class as argument. All objects that can be passed to the macro have to implement a specific marker trait.

The following snippet shows the marker trait and two example case classes implementing it:

trait Domain
case class Country( id: String, name: String ) extends Domain
case class Town( id: String, longitude: Double, latitude: Double ) extends Domain

Now, I would like to write the following code using macros to avoid the heaviness of runtime reflection and its thread unsafety:

object Test extends App {

  // instantiate example domain object
  val myCountry = Country( "CH", "Switzerland" )

  // this is a macro call
  logDomain( myCountry )
} 

The macro logDomain is implemented in a different project and looks similar to:

object Macros {
  def logDomain( domain: Domain ): Unit = macro logDomainMacroImpl

  def logDomainMacroImpl( c: Context )( domain: c.Expr[Domain] ): c.Expr[Unit] = {
    // Here I would like to introspect the argument object but do not know how?
    // I would like to generate code that prints out all val's with their values
  }
}

The macro’s purpose should be to generate code that – at runtime – outputs all values (id and name) of the given object and prints them as shown next:

id (String) : CH
name (String) : Switzerland

To achieve this, I would have to dynamically inspect the passed type argument and determine its members (vals). Then I would have to generate an AST representing the code that creates the log output. The macro should work regardless of what specific object implementing the marker trait “Domain” is passed to the macro.

At this point I am lost. I would appreciate if someone could give me a starting point or point me to some documentation? I am relatively new to Scala and have not found a solution in the Scala API docs or the Macro guide.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T06:07:43+00:00Added an answer on June 17, 2026 at 6:07 am

    Listing the accessors of a case class is such a common operation when you’re working with macros that I tend to keep a method like this around:

    def accessors[A: u.WeakTypeTag](u: scala.reflect.api.Universe) = {
      import u._
    
      u.weakTypeOf[A].declarations.collect {
        case acc: MethodSymbol if acc.isCaseAccessor => acc
      }.toList
    }
    

    This will give us all the case class accessor method symbols for A, if it has any. Note that I’m using the general reflection API here—there’s no need to make this macro-specific yet.

    We can wrap this method up with some other convenience stuff:

    trait ReflectionUtils {
      import scala.reflect.api.Universe
    
      def accessors[A: u.WeakTypeTag](u: Universe) = {
        import u._
    
        u.weakTypeOf[A].declarations.collect {
          case acc: MethodSymbol if acc.isCaseAccessor => acc
        }.toList
      }
    
      def printfTree(u: Universe)(format: String, trees: u.Tree*) = {
        import u._
    
        Apply(
          Select(reify(Predef).tree, "printf"),
          Literal(Constant(format)) :: trees.toList
        )
      }
    }
    

    And now we can write the actual macro code pretty concisely:

    trait Domain
    
    object Macros extends ReflectionUtils {
      import scala.language.experimental.macros
      import scala.reflect.macros.Context
    
      def log[D <: Domain](domain: D): Unit = macro log_impl[D]
      def log_impl[D <: Domain: c.WeakTypeTag](c: Context)(domain: c.Expr[D]) = {
        import c.universe._
    
        if (!weakTypeOf[D].typeSymbol.asClass.isCaseClass) c.abort(
          c.enclosingPosition,
          "Need something typed as a case class!"
        ) else c.Expr(
          Block(
            accessors[D](c.universe).map(acc =>
              printfTree(c.universe)(
                "%s (%s) : %%s\n".format(
                  acc.name.decoded,
                  acc.typeSignature.typeSymbol.name.decoded
                ),
                Select(domain.tree.duplicate, acc.name)
              )
            ),
            c.literalUnit.tree
          )
        )
      }
    }
    

    Note that we still need to keep track of the specific case class type we’re dealing with, but type inference will take care of that at the call site—we won’t need to specify the type parameter explicitly.

    Now we can open a REPL, paste in your case class definitions, and then write the following:

    scala> Macros.log(Town("Washington, D.C.", 38.89, 77.03))
    id (String) : Washington, D.C.
    longitude (Double) : 38.89
    latitude (Double) : 77.03
    

    Or:

    scala> Macros.log(Country("CH", "Switzerland"))
    id (String) : CH
    name (String) : Switzerland
    

    As desired.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a scala program that I would like to call from within django
I have a high CPU/memory bound task that I would like my Scala program
I would like to create a program that will run in background as a
I would like to create a program in a linux/unix environment that runs from
I would like to build an excel VBA program to find all the match
I would like to create a console program in VB.net that would allow parameters.
I'm implementing part of a Scala program that takes input strings of the form
I would like to program a computer game which should be played by several
I would like to change a program to automatically detect whether a terminal is
I would like to execute some program through ssh and redirect its input from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.