问题
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")
回答1:
This can be solved using scala Dynamic feature:
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)
}
when executing:
(-[Paris]-,-[Vallorbe]-)
来源:https://stackoverflow.com/questions/14876856/simple-scala-macro