Skip to content

Commit fd9b559

Browse files
committed
Added sample for string interpolation matching
1 parent df1fd61 commit fd9b559

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

scala-core-modules/scala-core/src/main/scala/com/baeldung/scala/patternmatching/PatternMatching.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,15 @@ class PatternMatching {
9191
}
9292
}
9393

94+
def stringInterpolationMatching(toMatch: String): String = {
95+
toMatch match {
96+
case s"$firstName.$lastName@$domain.$extension" =>
97+
s"Hey ${firstName.capitalize} ${lastName.capitalize}, $domain.$extension is your email domain"
98+
case s"$day-$month-${year}T$time" => s"$month $day, $year"
99+
case _ => "unknown pattern"
100+
}
101+
}
102+
94103
def optionsPatternMatching(option: Option[String]): String = {
95104
option match {
96105
case Some(value) => s"I'm not an empty option. Value $value"

scala-core-modules/scala-core/src/test/scala/com/baeldung/scala/patternmatching/PatternMatchingUnitTest.scala

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,30 @@ class PatternMatchingUnitTest {
155155
)
156156
}
157157

158+
@Test
159+
def whenEmailIsPassedWithComDomain_itShouldExtractParts(): Unit = {
160+
val result = new PatternMatching().stringInterpolationMatching("[email protected]")
161+
assertEquals("Hey James Kirk, starfleet.com is your email domain", result)
162+
}
163+
164+
@Test
165+
def whenEmailIsPassedWithCoInDomain_itShouldExtractParts(): Unit = {
166+
val result = new PatternMatching().stringInterpolationMatching("[email protected]")
167+
assertEquals("Hey James Kirk, starfleet.co.in is your email domain", result)
168+
}
169+
170+
@Test
171+
def whenDateTimeIsPassed_itShouldExtractDate(): Unit = {
172+
val result = new PatternMatching().stringInterpolationMatching("01-April-2024T10:20:30")
173+
assertEquals("April 01, 2024", result)
174+
}
175+
176+
@Test
177+
def whenUnknownDataIsPassed_itShouldReturnDefaultString(): Unit = {
178+
val result = new PatternMatching().stringInterpolationMatching("something-unknown.unmatched")
179+
assertEquals("unknown pattern", result)
180+
}
181+
158182
@Test
159183
def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = {
160184
val result =

0 commit comments

Comments
 (0)