Skip to content

Instantly share code, notes, and snippets.

@bwmcadams
Created January 18, 2011 18:04
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 bwmcadams/784852 to your computer and use it in GitHub Desktop.
Save bwmcadams/784852 to your computer and use it in GitHub Desktop.
Adding some Casbah object methods to Scala Maps
implicit def pimpMyMap(underlying: Map[_,_]) = new {
/** Lazy utility method to allow typing without conflicting with Map's required get() method and causing ambiguity */
def getAs[A <: Any : Manifest](key: Any): Option[A] = {
require(manifest[A] != manifest[scala.Nothing],
"Type inference failed; getAs[A]() requires an explicit type argument " +
"(e.g. mapObject.getAs[<ReturnType>](somegetAKey) ) to function correctly.")
underlying.get(key) match {
case null => None
case value => Some(value.asInstanceOf[A])
}
}
/**
* as
*
* Works like apply(), unsafe, bare return of a value.
* Returns default if nothing matching is found, else
* tries to cast a value to the specified type.
*
* Unless you overrode it, default throws
* a NoSuchElementException
*
* @param key (String)
* @tparam A
* @return (A)
* @throws NoSuchElementException
*/
def as[A <: Any : Manifest](key: Any) = {
require(manifest[A] != manifest[scala.Nothing],
"Type inference failed; as[A]() requires an explicit type argument" +
"(e.g. mapObject.as[<ReturnType>](someKey) ) to function correctly.")
underlying.get(key) match {
case null => default(key)
case value => value.asInstanceOf[A]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment