Created
January 18, 2011 18:04
-
-
Save bwmcadams/784852 to your computer and use it in GitHub Desktop.
Adding some Casbah object methods to Scala Maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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