2012-09-14 41 views
1

我在應用程序中使用了日誌記錄特徵,我很好奇是否可以從記錄特徵中訪問受保護的變量。如何訪問姐妹性狀中的受保護變量

這是我有:

class MyClass extends ExternalTrait with Logging 

trait ExternalTrait { 
    protected val protectedVar = "secret?" 
} 

trait Logging { 
    if(this.isInstanceOf[OtherTrait]) 
    this.asInstanceOf[OtherTrait].protectedVar 
} 

,但是以這種方式訪問​​時,受保護的變量的訪問受到限制。有沒有其他方法可以從Logging特性中訪問protectedVar?

非常感謝。

回答

3

如果你肯定知道Logging後混入到ExternalTrait你可以放置一個自我參考:

trait Logging { this: ExternalTrait => 
    val value = protectedVar 
} 

當然,如果可以有記錄不延長特質/混入其他性狀自我引用不合適。在這種情況下,我將繼承Logging以處理不同的行爲。

trait Logging 
trait StandAloneLogging extends Logging 
trait BasedOnLogging extends Logging { this: ExternalTrait => 
    val value = protectedVar 
} 
+0

我希望檢測和使用只有一個Logging特性作爲Scala提供的神奇解決方案,儘管您建議的擴展不是太侵入。 – mut1na