Scala 可变选项? [英] Scala Mutable Option?
本文介绍了Scala 可变选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要这样的东西:
private val cachedResponse = mutable.Option.empty[A]
def get: A = cachedResponse getOrElseUpdate db.findModel()
def update: Unit = {
db.updateModel
cachedResponse.empty() // set it to None/Option.empty
}
我不是在寻找一个通用的基于 HashMap 的备忘录像这样.我尝试使用 var Option[A]
来实现它,但对我来说它看起来不太习惯:
I am not looking for a generic HashMap based memoization like this. I tried implementing it using a var Option[A]
but it did not look very idiomatic to me:
private var cachedResponse: Option[A] = None
def get: A = cachedResponse getOrElse {
cachedResponse = Option(db.findModel())
cachedResponse.get
}
def update: Unit = {
db.updateModel
cachedResponse = None
}
推荐答案
标准库中没有内置方案.
There isn't one built into the standard library.
使用包含不可变 Option
的 var
是惯用的方法(假设您不能重写它以根本不使用状态).
Using a var
containing an immutable Option
is the idiomatic way to do it (assuming you can't rewrite this to not use state at all).
否则,您应该构建自己的.这是实现的核心:
Otherwise, you should build your own. Here's the core of an implementation:
class MutableOpt[A] {
private[this] var myValue: A = _
private[this] var loaded = false
private def valueEquals(o: Any) = myValue == o
def get = if (loaded) myValue else throw new NoSuchElementException("MutableOpt")
def set(a: A): this.type = { loaded = true; myValue = a; this }
def getOrSet(a: => A): A = {
if (!loaded) {
myValue = a
loaded = true
}
myValue
}
def isEmpty = !loaded
def nonEmpty = loaded
def foreach[U](f: A => U): Unit = if (loaded) f(myValue)
def transform(f: A => A): this.type = { if (loaded) myValue = f(myValue); this }
def clear(): this.type = { loaded = false; this }
def toOption = if (loaded) Some(myValue) else None
override def toString = if (loaded) "MutableOpt("+myValue.toString+")" else "MutableOpt()"
override def hashCode = if (loaded) myValue.hashCode else 1751
override def equals(o: Any) = o match {
case m: MutableOpt[_] =>
(isEmpty && m.isEmpty) || (nonEmpty && m.nonEmpty && m.valueEquals(myValue))
case _ => false
}
}
object MutableOpt {
def from[A](o: Option[A]) = {
val m = new MutableOpt[A]
o match {
case Some(a) => m set a
case _ =>
}
m
}
}
如果使用 REPL,请与 :paste
一起定义.
Define together with :paste
if using the REPL.
这篇关于Scala 可变选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文