Skip to content

Commit a9cc4b6

Browse files
Bryan ChapmanBryan Chapman
authored andcommitted
Add new example for default map values
1 parent 833496b commit a9cc4b6

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/main/scala/stdlib/Maps.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,20 @@ object Maps extends FlatSpec with Matchers with exercise.Section {
7878
myMap("IA") should be(res1)
7979
}
8080

81+
/** If a map key is requested using myMap(missingKey) which does not exist a NoSuchElementException will be thrown.
82+
* Default values may be provided using either getOrElse or withDefaultValue for the entire map
83+
*/
84+
def defaultValuesMayBeProvidedMaps(res0: String, res1: String) {
85+
val myMap = Map("MI" "Michigan", "OH" "Ohio", "WI" "Wisconsin", "IA" "Iowa")
86+
intercept[NoSuchElementException] {
87+
myMap("TX")
88+
}
89+
myMap.getOrElse("TX", "missing data") should be(res0)
90+
91+
val myMap2 = Map("MI" "Michigan", "OH" "Ohio", "WI" "Wisconsin", "IA" "Iowa") withDefaultValue "missing data"
92+
myMap2("TX") should be(res1)
93+
}
94+
8195
/** Map elements can be removed easily:
8296
*/
8397
def easilyRemovedMaps(res0: Boolean, res1: Boolean) {

0 commit comments

Comments
 (0)