这是我在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?
答案 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)