gpt4 book ai didi

Scala 可变选项?

转载 作者:行者123 更新时间:2023-12-04 19:05:25 24 4
gpt4 key购买 nike

我想要这样的东西:

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 的内存 like this .我尝试使用 var Option[A] 来实现它但对我来说它看起来不太习惯:
private var cachedResponse: Option[A] = None

def get: A = cachedResponse getOrElse {
cachedResponse = Option(db.findModel())
cachedResponse.get
}

def update: Unit = {
db.updateModel
cachedResponse = None
}

最佳答案

标准库中没有内置。

使用 var包含一个不可变的 Option是惯用的方式来做到这一点(假设你不能重写它根本不使用状态)。

否则,您应该构建自己的。这是一个实现的核心:

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
}
}

:paste 一起定义如果使用 REPL。

关于Scala 可变选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com