【发布时间】:2018-04-10 17:07:40
【问题描述】:
我想使用函数的方式在 scala 中存储一个状态 (key -> value)。大概是以前在奥德斯基的课上学过的,但是记不住了。
这是我的非功能性方法;
import org.scalatest.{FunSuite, Matchers}
trait EventHandler
class StatefulNonFn {
type EventName = String
private var state = Map.empty[EventName, EventHandler]
def update(name: String): EventHandler = {
state.get(name).fold {
val handler = new EventHandler {}
state += name -> handler
handler
}(eh => eh)
}
}
class NonFunctionalStateSpec extends FunSuite with Matchers {
test("stateful") {
val stateResult = new StatefulNonFn().update("MusicAdded")
stateResult.isInstanceOf[EventHandler] shouldBe true
}
}
我所做的一个尝试是使状态成为“EventName 和 previousState 的函数”,这是有道理的,但现在我不知道如何存储所有这些状态?
我的第一个电话会很好,因为在那种情况下状态是空的。
import org.scalatest.{FunSuite, Matchers}
trait EventHandler
class Stateful {
type EventName = String
private val stateFn = new ((String, Map[EventName, EventHandler]) => Map[EventName, EventHandler]) {
override def apply(name: String, prevState: Map[EventName, EventHandler]): Map[EventName, EventHandler] = {
val handler = new EventHandler {}
prevState + (name -> handler)
}
}
def initState = Map.empty[EventName, EventHandler]
def update(name: String, prevState: Map[EventName, EventHandler]) = stateFn(name, prevState)
}
class FunctionalStateSpec extends FunSuite with Matchers {
test("stateful") {
val stateHelper = new Stateful()
val stateResult = stateHelper.update("MusicAdded", stateHelper.initState)
stateResult.keys.size shouldBe 1
val stateResult1 = stateHelper.update("MusicDeleted", stateResult)
stateResult1.keys.size shouldBe 2
//what i obviously want is something like this without me wanting to store the previousStates
//stateHelper.update("MusicAdded1")
//stateHelper.update("MusicAdded2")
}
}
我不确定,也许某些东西最终必须是可变的。在上述情况下如何存储以前的状态?没有客户在每次通话中提供它。因为可以从 5 个不同的客户端更新状态,而无需知道之前的状态。
【问题讨论】:
标签: scala functional-programming