Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Maps.scala #138

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/main/scala/stdlib/Maps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -160,5 +160,17 @@ object Maps extends FlatSpec with Matchers with org.scalaexercises.definitions.S

myMap1.equals(myMap2) should be(res0)
}

/** Map access elements with .get(missingKey) handles nonexistent element gracefully returning Option, instead of throwing `NoSuchElementException` when using `myMap(missingKey)`:
*/
def accessMissingElements(res0: Option[String], res1: Option[String]) {
val myMap =
Map("MI" → "Michigan", "OH" → "Ohio", "WI" → "Wisconsin", "IA" → "Iowa")
intercept[NoSuchElementException] {
myMap("TX")
}
myMap.get("MI") should be(res0)
myMap.get("TX") should be(res1)
}

}
19 changes: 19 additions & 0 deletions src/main/scala/stdlib/PatternMatching.scala
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,23 @@ object PatternMatching extends FlatSpec with Matchers with org.scalaexercises.de
r == Nil should be(res0)
}


/** Pattern matching allows complex parsing and assigning an alias(using @) to each part of the parsed type:
*/
def patmatComplexType(res0: String, res1:String, res2: String) {
case class Person(name: String, age: Int) {
def me = "I'm person"
}

case class Employee(person: Person, job: String) {
def me = "I'm employee"
}

val res = Employee(Person("John", 23), "Janitor") match {
case e@Employee(p@Person(_, _), job) =>
(e.me, p.me, job)
case _ =>
}
res should be ((res0,res1,res2))
}
}