2013-06-19 31 views
1

更多a 假设问题。它是可能,使用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) 

这是天堂类型 - 宏是什么?

如果是这样,为什么有人想停止类型宏的发展?

+1

我想这绝对是返回'Template'树的类型宏,就像[本文档]中的最后一个示例(http://docs.scala-lang.org/overviews/macros/typemacros.html#intuition )。 – gourlaysama

回答

3

是的,那是什么类型的宏被设计来做。他们被抛弃了,因为他们也可以做其他我们不确定暴露的事情。不过,我们认识到代码生成的价值,目前我们正在探索实现代码生成的其他途径(例如宏注释)。