Skip to content

Instantly share code, notes, and snippets.

Created March 9, 2013 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/5124500 to your computer and use it in GitHub Desktop.
Save anonymous/5124500 to your computer and use it in GitHub Desktop.
class EnumMap[K <: Enum[_], +T] private (values: Array[T])
(implicit m: Manifest[K])
extends Map[K, T] {
def this()(implicit k: Manifest[K], t: Manifest[T]) =
this(t.newArray(k.erasure.getEnumConstants.length))(k)
val notNulls = values.count(_ != null)
def get(key: K) = {
val value = values(key.ordinal())
if (value != null) Some(value) else None
}
def iterator = new Iterator[(K, T)] {
var index: Int = -1;
def hasNext = index < notNulls - 1
@tailrec
private def nextNonNullIndex(index:Int):Int=
if (values(index)!=null) index
else nextNonNullIndex(index+1)
def next() = {
val value = values(nextNonNullIndex(index+1));
val key = m.erasure.getEnumConstants()(index).asInstanceOf[K]
(key, value)
}
}
def -(key: K) = get(key) match {
case None => this
case Some(_) => {
this.+((key, null))
}
}
def +[B1 >: T](kv: (K, B1)) = {
val newArray = values.clone()
newArray(kv._1.ordinal()) = kv._2.asInstanceOf[T]
new EnumMap(newArray)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment