我想要一个执行以下操作的scala宏: 我写的时候:
myCreateCityMacro("paris")
myCreateCityMacro("vallorbe")
我想得到:
val paris = new City("paris")
val vallorbe = new City("vallorbe")
答案 0 :(得分:0)
这可以使用scala动态功能解决:
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)
}
执行时:
(-[Paris]-,-[Vallorbe]-)