From 30d8fe033ebe3c77bdfe34b87017abc5a132255f Mon Sep 17 00:00:00 2001 From: Christos KK Loverdos Date: Thu, 9 Feb 2012 17:40:52 +0200 Subject: [PATCH] Add map-related utility methods --- .../scala/gr/grnet/aquarium/util/package.scala | 35 ++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/main/scala/gr/grnet/aquarium/util/package.scala b/src/main/scala/gr/grnet/aquarium/util/package.scala index b81ab86..715717e 100644 --- a/src/main/scala/gr/grnet/aquarium/util/package.scala +++ b/src/main/scala/gr/grnet/aquarium/util/package.scala @@ -35,6 +35,9 @@ package gr.grnet.aquarium +import com.ckkloverdos.maybe.{Just, NoVal, Maybe} + + /** * Utility definitions. * @@ -84,4 +87,36 @@ package object util { def displayableObjectInfo(obj: AnyRef): String = { "[%s] %s".format(obj.getClass, obj) } + + /** + * This basically turns an [[scala.Option]] into a [[com.ckkloverdos.maybe.Maybe]] when asking a [[scala.collection.Map]] + * for a key. + * + * @param map The input map. + * @param key The key we are interested in. + * @tparam A The type of keys. + * @tparam B The type of values. + * + * @return A [[com.ckkloverdos.maybe.Just]] if a value was found, a + * [[com.ckkloverdos.maybe.NoVal]] if nothing was found and a + * [[com.ckkloverdos.maybe.Failed]] if some error happened. + */ + def findFromMapAsMaybe[A, B <: AnyRef](map: scala.collection.Map[A, B], key: A): Maybe[B] = Maybe { + map.get(key) match { + case Some(value) ⇒ + value + case None ⇒ + null.asInstanceOf[B] + } + } + + def findAndRemoveFromMap[A, B <: AnyRef](map: scala.collection.mutable.Map[A, B], key: A): Maybe[B] = Maybe { + map.get(key) match { + case Some(value) ⇒ + map -= key + value + case None ⇒ + null.asInstanceOf[B] + } + } } \ No newline at end of file -- 1.7.10.4