斯卡拉替换,否则用状态设计模式

时间:2019-03-12 14:35:34

标签: scala if-statement state

这是我在Scala中的if语句代码:

package calculator

class Calculator() {
  var num = 0.0
  var count = 0

  def displayNumber(): Double = {
    num
  }

}

def handle(): Unit = {
    if (calculator.num == 0.0){
        calculator.num = number
      }
    else{
        calculator.num = calculator.num * 10 + number
      }
    }

如何用状态模式替换if-else?

1 个答案:

答案 0 :(得分:2)

你是说州立单子吗?

  import cats.data.State

  val number = 20.0

  case class Calculator(num: Double, count: Int)

  def state: State[Calculator, Unit] = for {
    calculator <- State.get[Calculator]
    _ <- State.set(if (calculator.num == 0.0) calculator.copy(num = number) else calculator.copy(num = calculator.num * 10 + number))
  } yield ()

  state.runS(Calculator(0.0, 0)).value // Calculator(20.0,0)