更多的是假设性问题。是否有可能使用 Scala 宏来转换这样的结构:
object Foo extends Factory { // Factory = expansion magic
trait Config {
val i: Int = 33
val s: String = "foo"
}
def apply(c: Config): Foo = ???
}
trait Foo
(或多或少自动)进入这个:
object Foo {
sealed trait ConfigLike {
def i: Int
def s: String
}
object Config {
def apply() = new ConfigBuilder
implicit def build(b: ConfigBuilder) = b.build
}
final case class Config(i: Int, s: String) extends ConfigLike
object ConfigBuilder {
def apply(c: Config) = {
val b = new ConfigBuilder
b.read(c)
b
}
}
final class ConfigBuilder extends ConfigLike {
var i: Int = 33
var s: String = "foo"
def build: Config = Config(i, s)
def read(c: Config) {
i = c.i
s = c.s
}
}
def apply(c: Config = Config()): Foo = ???
}
用例:
val c = Foo.Config()
c.i = 44
c.s = "bar"
val f = Foo(c)
这是天堂类型宏的用途吗?
如果是这样,为什么有人要停止类型宏的开发?