3

我想要一个执行以下操作的 scala 宏:当我编写时:

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

我想得到:

val paris = new City("paris")
val vallorbe = new City("vallorbe")
4

1 回答 1

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]-)
于 2014-02-25T09:56:04.753 回答