From a9cc4b64355ce954734b0fccfbfd74fcfa3d6650 Mon Sep 17 00:00:00 2001 From: Bryan Chapman Date: Tue, 28 Jun 2016 10:43:39 -0500 Subject: [PATCH 1/2] Add new example for default map values --- src/main/scala/stdlib/Maps.scala | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/main/scala/stdlib/Maps.scala b/src/main/scala/stdlib/Maps.scala index 3bf1aeb3..442028d9 100644 --- a/src/main/scala/stdlib/Maps.scala +++ b/src/main/scala/stdlib/Maps.scala @@ -78,6 +78,20 @@ object Maps extends FlatSpec with Matchers with exercise.Section { myMap("IA") should be(res1) } + /** If a map key is requested using myMap(missingKey) which does not exist a NoSuchElementException will be thrown. + * Default values may be provided using either getOrElse or withDefaultValue for the entire map + */ + def defaultValuesMayBeProvidedMaps(res0: String, res1: String) { + val myMap = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") + intercept[NoSuchElementException] { + myMap("TX") + } + myMap.getOrElse("TX", "missing data") should be(res0) + + val myMap2 = Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa") withDefaultValue "missing data" + myMap2("TX") should be(res1) + } + /** Map elements can be removed easily: */ def easilyRemovedMaps(res0: Boolean, res1: Boolean) { From bfdac1c6f18829d7316d90b0b5e7b3f021f46708 Mon Sep 17 00:00:00 2001 From: Bryan Chapman Date: Tue, 28 Jun 2016 10:48:48 -0500 Subject: [PATCH 2/2] Add test case for default map values --- src/test/scala/exercises/stdlib/MapSpec.scala | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/test/scala/exercises/stdlib/MapSpec.scala b/src/test/scala/exercises/stdlib/MapSpec.scala index dbb73373..268e0d74 100644 --- a/src/test/scala/exercises/stdlib/MapSpec.scala +++ b/src/test/scala/exercises/stdlib/MapSpec.scala @@ -72,6 +72,15 @@ class MapsSpec extends Spec with Checkers { ) } + def `map default value access` = { + check( + Test.testSuccess( + Maps.defaultValuesMayBeProvidedMaps _, + "missing data" :: "missing data" :: HNil + ) + ) + } + def `map element removal` = { check( Test.testSuccess(