Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.baeldung.scala.patternmatching

sealed trait Command
case object Start extends Command
case object Stop extends Command
case object Report extends Command
case class CustomCommand(cmd: String) extends Command

def executeCommand(command: Command): String = command match {
case Start | CustomCommand("begin") =>
"System Starting."
case Stop | CustomCommand("halt") =>
"System Stopping."
case Report | CustomCommand("status") =>
"Generating Report."
case _ =>
"Unknown Command."
}

def httpResponse(response: Int): String = response match {
case 200 | 201 | 202 => "Success"
case 400 | 404 | 500 => "Error"
case _ => "Unknown status"
}

def multipleTypePatterns(obj: Any): String = obj match {
case _: String | _: Int => "It's either a String or an Int"
case _ => "It's something else"
}

def unionTypePattern(obj: Any): String = obj match {
case _: (String | Int) => "It's either a String or an Int"
case _ => "It's something else"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.baeldung.scala.patternmatching

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class MultipleMatchesUnitTest extends AnyFlatSpec with Matchers {

"executeCommand" should "start the system when given the command" in {
val result = executeCommand(Start)
result shouldEqual "System Starting."
}

it should "stop the system when given the command" in {
val result = executeCommand(CustomCommand("halt"))
result shouldEqual "System Stopping."
}

"httpResponse" should "Error" in {
val result = httpResponse(404)
result shouldEqual "Error"
}

"multipleTypePatterns" should "Error" in {
val result = multipleTypePatterns(4.4)
result shouldEqual "It's something else"
}

"unionTypePattern" should "Error" in {
val result = unionTypePattern(42)
result shouldEqual "It's either a String or an Int"
}

}