Search code examples
scalacachingsortedmap

Scala SortedMap gets complained


I'm trying to create a simple cache class, mimicking Map, in Scala, and it looks like this currently:


import scala.collection.mutable.{Map, SortedMap}

class LRUCache[K, V](private val capacity: Int) extends Map[K, V]:
  private var cache = SortedMap.empty[K, V]

  def lru: Seq[K] = this.cache.keys.toSeq

  def length: Int = this.cache.size

  override def get(key: K): Option[V] = this.cache.get(key)

  override def getOrElse[V1 >: V](key: K, default: => V1): V1 = this.get(key) match
      case Some(value) => value
      case None => default

  override def iterator: Iterator[(K, V)] = ???

  override def addOne(elem: (K, V)): LRUCache.this.type =
    if this.cache.size < this.capacity then
      this.cache.addOne(elem)
    this

  override def subtractOne(elem: K): LRUCache.this.type = ???

  override def clear(): Unit = cache.clear()

  override def contains(key: K): Boolean = cache.contains(key)

But the compiler gives me an error that I cannot understand:

No implicit Ordering defined for K..
I found:

    scala.math.Ordering.ordered[K](
      /* missing */summon[scala.math.Ordering.AsComparable[K]]
    )

But no implicit values were found that match type scala.math.Ordering.AsComparable[K].
  private var cache = SortedMap.empty[K, V]

Solution

  • You need to provide a constraint for K. For example change your class definition to:

    class LRUCache[K:Ordering, V](private val capacity: Int) extends Map[K, V]: