simple scala macro

℡╲_俬逩灬. 提交于 2019-12-23 17:19:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!