gpt4 book ai didi

scala - 简单的scala宏

转载 作者:行者123 更新时间:2023-12-04 18:01:21 24 4
gpt4 key购买 nike

我想要一个执行以下操作的 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]-)

关于scala - 简单的scala宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com