2012-03-05 50 views
5

对不起,如果这是一个愚蠢的标题,我不知道该如何表达这显然斯卡拉 - 通过自我类型注解类子对象

说,我有一个日志特质:

trait Logging { 
    def log(s:String) 
} 

,然后一些实施

trait PrintlnLog extends Logging { 
    def log(s:String) { println(s) } 
} 

,我用这样

class SomeProcess { this:Logging => 
    def doSomeJunk() { 
     log("starting junk") 
     ... 
     log("junk finished") 
    } 
} 

我可以使用这个类像

val p = new SomeProcess() with PrintLog 
p.doSomeJunk() 

现在如果我有这个

class SubProcess { this:Logging => 
    def doSubJunk() { 
     log("starting sub junk") 
     ... 
     log("finished sub junk") 
    } 
} 

class ComplexProcess { this:Logging => 
    def doMoreJunk() { 
     log("starting more junk") 
     val s = new SubProcess with // ??? <-- help! 
     s.doSubJunk() 
     log("finished more junk") 
    } 
} 
在ComplexProcess

我想实例化一个子过程中已经混入ComplexProcess相同的日志特质的混合,但ComplexProcess不知道那是什么。有没有办法得到它的参考?

回答

4

你不能那样做。在这种情况下,你可能会这样做:

trait WithSubProcess { 
    def s: SubProcess 
} 

class ComplexProcess { this: Logging with WithSubProcess ... } 
+0

这实际上就是我在做的事情,但它很丑,因为我具有散布在我的代码中的所有这些特征,其唯一目的是为了记录日志。希望有更好的办法 – dvmlls 2012-03-05 19:47:10

2

答案根据定义,不是。 Scala是一种静态类型的语言,因此这些信息仅在编译时才可用。 Paolo提到,使用更广泛的反射API和一些组合/组装黑客可能在将来有可能实现,尽管这与Paolo提到的面向方面编程接近。