2012-03-04 38 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