Skip to content

Commit e60f1d6

Browse files
Merge pull request #1319 from oforero/SCALA-724
SCALA-724: Code companion for the article.
2 parents 3f7457c + 4b62af3 commit e60f1d6

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.scala.patternmatching
2+
3+
sealed trait Command
4+
case object Start extends Command
5+
case object Stop extends Command
6+
case object Report extends Command
7+
case class CustomCommand(cmd: String) extends Command
8+
9+
def executeCommand(command: Command): String = command match {
10+
case Start | CustomCommand("begin") =>
11+
"System Starting."
12+
case Stop | CustomCommand("halt") =>
13+
"System Stopping."
14+
case Report | CustomCommand("status") =>
15+
"Generating Report."
16+
case _ =>
17+
"Unknown Command."
18+
}
19+
20+
def httpResponse(response: Int): String = response match {
21+
case 200 | 201 | 202 => "Success"
22+
case 400 | 404 | 500 => "Error"
23+
case _ => "Unknown status"
24+
}
25+
26+
def multipleTypePatterns(obj: Any): String = obj match {
27+
case _: String | _: Int => "It's either a String or an Int"
28+
case _ => "It's something else"
29+
}
30+
31+
def unionTypePattern(obj: Any): String = obj match {
32+
case _: (String | Int) => "It's either a String or an Int"
33+
case _ => "It's something else"
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.scala.patternmatching
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
6+
class MultipleMatchesUnitTest extends AnyFlatSpec with Matchers {
7+
8+
"executeCommand" should "start the system when given the command" in {
9+
val result = executeCommand(Start)
10+
result shouldEqual "System Starting."
11+
}
12+
13+
it should "stop the system when given the command" in {
14+
val result = executeCommand(CustomCommand("halt"))
15+
result shouldEqual "System Stopping."
16+
}
17+
18+
"httpResponse" should "Error" in {
19+
val result = httpResponse(404)
20+
result shouldEqual "Error"
21+
}
22+
23+
"multipleTypePatterns" should "Error" in {
24+
val result = multipleTypePatterns(4.4)
25+
result shouldEqual "It's something else"
26+
}
27+
28+
"unionTypePattern" should "Error" in {
29+
val result = unionTypePattern(42)
30+
result shouldEqual "It's either a String or an Int"
31+
}
32+
33+
}

0 commit comments

Comments
 (0)