More Scala Pattern Matching

Question Click to View Answer

What does the following code return?

val someInt: Int = 123
someInt match {
  case 123 => I am an integer
  case _ => I'm not an int
}

"I am an integer" is returned.

someInt is an integer value. Values can be matched directly when pattern matching.

What does the following code return?

case class Dog(firstName: String)
val myDog = Dog("fido")
myDog match {
  case Dog(firstName) => "My dog's name is " + firstName
  case _ => "Invalid Int"
}

"My dog's name is fido" is returned.

We were able to pattern match an object and extract a value from the object.

What does the following code return?

val someNum = Option(1)
someNum match {
  case Some(v: Int) => v + 3
  case None => "I don't know what to do"
}

4 is returned, but it has the Any type. It's not an integer value.

What does the following code return?

val list: List[Option[Int]] = List(Some(1), None, Some(2))
val result: List[Int]=list.map( numberOpt => numberOpt match {
  case Some(v) => v
  case None => 0
})

List(1, 0, 2) is returned.

What does the following code return?

"1,2,3".split(",").toList match {
  case first :: second :: third :: Nil => "Counting Practice"
  case _ => throw new Exception("This is not what I expected")
}

"Counting Practice" is returned.

What does the following code return?

def multiply(list: List[Int]): Int = list match {
  case Nil => 1
  case n :: rest => n * multiply(rest)
}

multiply(List(1,2,3,4))

24 is returned.

Pattern matching can be used to multiply all the values in a list.

What does the following code return?

def dateFormatter(someDate: Any): String = someDate match {
  case d: java.time.LocalDate => d.toString()
  case s: String => s
  case _ => "Not sure what this is"
}

dateFormatter("2019-03-04")
dateFormatter(java.time.LocalDate.parse("2020-01-01"))
dateFormatter(42)

Here are the function inputs and the associated return values:

dateFormatter("2019-03-04") // "2019-03-04"
dateFormatter(java.time.LocalDate.parse("2020-01-01")) // "2020-01-01"
dateFormatter(42) // "Not sure what this is"

Pattern matching is a great way to handle different types of input values with custom logic.

If you have an unknown value, you can handle it differently depending on it's type.

This type based logic is one of the most powerful features of the Scala programming language.