0

I'm new to Scala macros, so sorry if this is an obvious question.

I wonder if the following is even possible before I dig in deeper.

Let's say I have a class named DynamicProperties

Is it possible to add members to the class based on something like this?

val x: DynamicProperties = ...
x.addProperty("foo", 1) 
x.addProperty("bar", true)
x.addProperty("baz", "yep")

and have it be translated somehow to a class that looks like this more or less?

class SomeName extends DynamicProperties { 
   val foo: Int = 1
   val bar: Boolean = true
   val baz: String: yep
}

I guess this can be done via reflection, but I want people who use this, to have auto complete when they type x. that will fit what they did earlier using the addProperty method. Is this possible using Scala marcos? I want to try to implement it, but it will be good to know if this is going down a dead end path or not.

Eran Medan
  • 44,555
  • 61
  • 184
  • 276
  • I think you need macro annotations for this, which aren't in standard Scala. They live in "macro paradise"; see http://docs.scala-lang.org/overviews/macros/annotations.html. But I'm a Scala macro noob so somebody should confirm. – Seth Tisue Apr 26 '15 at 03:51
  • 2
    Wouldn't it be easier to use the `Dynamic` trait? – Ryan Apr 26 '15 at 05:05
  • Yes, this is what I actually use now, but I want it to be used in auto complete. also in dynamic I won't have a compile time error if the user of the API specifies a missing property on x. – Eran Medan Apr 26 '15 at 14:49
  • It is currently impossible to do what you'd like with macros. Macros are about local transformations of code, so even if you declare `addProperty` as a macro, you won't be able to change the definition of x (you'll be able to read it, but not write it). You can, however, have `addProperty` return another object which contains all the properties of the input plus an additional one. – Eugene Burmako Apr 26 '15 at 19:37

0 Answers0