2012-03-04 39 views
1

我想用一些具有默認值的參數來定義一個case類,但默認值需要一個隱式參數。我已經試過這樣的事情:用隱式參數重載case類構造函數?

case class ChannelLatches(started: TestLatch, stopped: TestLatch)(implicit system: ActorSystem) { 
    def this()(implicit system: ActorSystem) = this(new TestLatch(), new TestLatch())(system) 
} 

這:

case class ChannelLatches(started: TestLatch, stopped: TestLatch)(implicit system: ActorSystem) { 
    def this()(implicit system: ActorSystem) = this(new TestLatch(), new TestLatch())(system) 
} 

但在這兩種情況下,編譯器無法識別我的新的構造。任何指針?

+0

案例類ChannelLatches(開始:TestLatch =新TestLatch,停止:TestLatch =新TestLatch)(隱含的系統:ActorSystem){ } – Eastsun 2012-03-04 05:21:35

+0

這是我試過的,可是編譯器會產生這樣的錯誤:找不到參數系統的隱式值:akka.actor.ActorSystem。我假設因爲系統是在後續的參數列表中定義的。 – jxstanford 2012-03-04 06:20:47

回答

4

問題不在案例類或其構造函數中。當你得到像

scala> val channelLatches = new ChannelLatches 
<console>:11: error: could not find implicit value for parameter system: ActorSystem 
     val channelLatches = new ChannelLatches 
          ^

編譯錯誤,這意味着你不必型ActorSystem的可作爲範圍單一的標識符的隱含變量。

無論你的代碼示例(它們是完全相同的代碼,對吧?),並@東日的例子是完全合法的代碼:

scala> class ActorSystem 
defined class ActorSystem 

scala> class TestLatch 
defined class TestLatch 

scala> case class ChannelLatches(started: TestLatch = new TestLatch, stopped: TestLatch = new TestLatch)(implicit system: ActorSystem) 
defined class ChannelLatches 

scala> implicit val actor = new ActorSystem 
actor: ActorSystem = [email protected] 

scala> val channelLatches = new ChannelLatches 
channelLatches: ChannelLatches = ChannelLatches([email protected],[email protected]) 

注意隱含的VAL演員這使得編譯器供應隱含地缺少參數。

約隱含參數的介紹請參見A Tour of Scala: Implicit Parameters

---編輯2012-03-05:新增的替代例子ChannelLatches是內部類的東西

如果你想ChannelLatches是一個內部類的東西,你真的不需要通過ActorSystem實例添加到內部類實例中,因爲內部類可以訪問外部對象的值。 A Tour of Scala: Inner Classes

scala> class ActorSystem 
defined class ActorSystem 

scala> class TestLatch 
defined class TestLatch 

scala> class Something(implicit val as: ActorSystem) { 
    | case class ChannelLatches(started: TestLatch, stopped: TestLatch) { 
    |  def this() = this(new TestLatch(), new TestLatch()) 
    | 
    |  def actorSystem = as 
    | } 
    | } 
defined class Something 

scala> implicit val as = new ActorSystem 
as: ActorSystem = [email protected] 

scala> val s = new Something 
s: Something = [email protected] 

scala> val cl = new s.ChannelLatches 
cl: s.ChannelLatches = ChannelLatches([email protected],[email protected]) 

scala> cl.actorSystem == as 
res0: Boolean = true 
+0

我試圖找到一種方法來讓ChannelLatches不是某個隱式系統的內部類。這就是爲什麼我要定義case類的隱式參數(當然,這在這種情況下不起作用)。 ActorSystem需要由調用者提供。 – jxstanford 2012-03-04 23:14:07