Simple scala macro

I would like to have a scala macro that does the following: When I write:

myCreateCityMacro("paris") myCreateCityMacro("vallorbe") 

I would like to get:

 val paris = new City("paris") val vallorbe = new City("vallorbe") 
+3
scala-macros
Feb 14 '13 at 14:19
source share
1 answer

This can be solved using the scala dynamic function:

 import scala.language.dynamics object Cities extends App { var c = new DynamicMap[String, City]() createCity("Paris") createCity("Vallorbe") println(c.Paris, c.Vallorbe) def createCity(name: String) { c.self.update(name, new City(name)) } } class City(name: String) { override def toString = s"-[$name]-" } class DynamicMap[K, V] extends Dynamic { val self = scala.collection.mutable.Map[K, V]() def selectDynamic(key: K) = self(key) } 

while doing:

 (-[Paris]-,-[Vallorbe]-) 
0
Feb 25 '14 at 9:56
source share



All Articles