我想要一个执行以下操作的 scala 宏:当我编写时:
myCreateCityMacro("paris")
myCreateCityMacro("vallorbe")
我想得到:
val paris = new City("paris")
val vallorbe = new City("vallorbe")
我想要一个执行以下操作的 scala 宏:当我编写时:
myCreateCityMacro("paris")
myCreateCityMacro("vallorbe")
我想得到:
val paris = new City("paris")
val vallorbe = new City("vallorbe")
这可以使用 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]-)