Scala案例类和私有构造函数元素

时间:2013-12-12 00:01:19

标签: scala case-class

我希望能够跟踪某个状态机中完成的任务数量(使用Akka FSM),这就像加入N个动作一样,从状态B开始从状态A转换到B,所以当所有的evens都达到FSM时状态B - 它进入状态C。

我为fork / join状态创建了非常简单的跟踪器。

  sealed trait ForkJoin {

    def join(): ForkJoin

  }

  case class Forks(forkNum: Int) extends ForkJoin {

    private var finished: Int = 0

    override def join = if (finished + 1 == forkNum) JoinComplete
    else {
      val f = Forks(forkNum)
      f.finished = finished + 1
      f
    }

  }

  case object JoinComplete extends ForkJoin {

    override def join = JoinComplete

  }

我不喜欢那里 - var完成的pewsense。它本质上是 val ,但我不知道如何制作私有val并在 join 方法中初始化它。

我认为有一些方法可以将构造函数参数设置为 private ,无法从外部访问 - 但这不起作用。

2 个答案:

答案 0 :(得分:4)

无法将私有参数传递给case classes。它没有意义,因为case类的实例的标识是在传递的构造函数参数上定义的。私有构造函数参数将更改状态,但不会影响相等比较和模式匹配。

你可以做的是制作整个构造函数private。要在FSM状态下正常运行,您可能需要在自己[1]上实施equalshashCode

sealed trait ForkJoin {
  def join(): ForkJoin
}

case class Forks private(forkNum: Int, finished: Int) extends ForkJoin{

  override def join =
    if (finished + 1 == forkNum)
      JoinComplete
    else
      Forks(forkNum, finished + 1)

  def copy(forkNum: Int = this.forkNum) = 
    Forks(forkNum, finished)

}

object Forks{
  def apply(forkNum: Int): Forks = Forks(forkNum, 0)
}

object JoinComplete extends ForkJoin {
  override def join = JoinComplete
}

答案 1 :(得分:1)

类似的东西?

sealed trait ForkJoin {
    def join(): ForkJoin
 }

  case class Forks(forkNum: Int, finished: Int = 0) extends ForkJoin {
    override def join = if (finished + 1 == forkNum) JoinComplete
    else Forks(forkNum, finished + 1)
   }

  case object JoinComplete extends ForkJoin {
    override def join = JoinComplete
  }