Created
April 23, 2018 20:15
-
-
Save kubukoz/98e1bd2d551cc7ad811b249abc982bd9 to your computer and use it in GitHub Desktop.
This file contains 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
object map { | |
/** | |
* Allows a Map to become total forever. | |
* It's isomorphic to `Map.withDefaultValue`, but has a more specific return type, in particular: | |
* <ul> | |
* <li>it leaves out the information that the returned value is a Map</li> | |
* <li>it manifests that the returned value is a total function.</li> | |
* </ul> | |
* | |
* This is useful for a single reason - Maps by default aren't total functions, so `map.apply` can potentially | |
* throw an exception. To make working with maps easier, a standard library function exists, | |
* namely `withDefaultValue`, that allows the caller to provide a default value that'll be used | |
* whenever `apply` is called with a key not recognized by the map. | |
* <br/><br/> | |
* | |
* There's a significant reason why you wouldn't want to use `withDefaultValue` instead - any transformation you apply | |
* on it (map, filter, flatMap, etc.) will render `withDefaultValue` useless - the default value will never be used, | |
* and the resulting Map's `apply` method can legally throw an exception. | |
*/ | |
implicit class TotalMap[K, V](val map: Map[K, V]) extends AnyVal { | |
def totalWithDefault[V1 >: V](default: V1): K => V1 = map.getOrElse(_, default) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment