gpt4 book ai didi

scala 类型问题 : SoftReference, ReferenceQueues, SoftHashMap

转载 作者:行者123 更新时间:2023-12-01 11:57:53 24 4
gpt4 key购买 nike

编辑 到目前为止,大多数答案都集中在我错误地扩展 map 这一事实上。我已在示例代码中更正了此问题,但类型问题仍然存在,问题仍然存在。

我试图在 Scala 中实现 SoftHashMap,但遇到了类型不匹配错误:

inferred type arguments [K,V] do not conform to class SoftValue's type parameter bounds [K,+V <: AnyRef]
val sv = new SoftValue(kv._1, kv._2, queue)

我知道我过度限制了类型,但我不确定如何解决它。

import scala.collection.mutable.{Map, HashMap}    
import scala.ref._

class SoftValue[K, +V <: AnyRef](val key:K, value:V, queue:ReferenceQueue[V]) extends SoftReference(value, queue)

class SoftMap[K, V] extends Map[K, V]
{
private val map = new HashMap[K, SoftValue[K, V]]

private val queue = new ReferenceQueue[V]

override def +=(kv: (K, V)):this.type =
{
val sv = new SoftValue(kv._1, kv._2, queue)
map(kv._1) = sv
this
}
}

最佳答案

这编译。 (编辑:我最初添加了 val value 但这创建了一个强有力的引用)。不确定您要如何处理迭代器...

import scala.collection.mutable.{Map, HashMap}    
import scala.ref._

class SoftValue[K, +V <: AnyRef](val key:K, value:V,
queue:ReferenceQueue[V]) extends SoftReference(value, queue)

class SoftMap[K, V <: AnyRef] extends Map[K, V] {
private val map = new HashMap[K, SoftValue[K, V]]
private val queue = new ReferenceQueue[V]

def +=(kv: (K, V)): this.type = {
val sv = new SoftValue(kv._1, kv._2, queue)
map(kv._1) = sv
this
}

def -=(k: K): this.type = { map -= k; this }
def get(k: K) = map.get(k).flatMap(_.get)
def iterator: Iterator[(K,V)] = error("todo")
}

你错过了 V <: AnyRef定义 SoftMap 时, 所以 V 可以用作 SoftValue 的参数构造函数

关于scala 类型问题 : SoftReference, ReferenceQueues, SoftHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5124969/

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