|
| 1 | +package com.baeldung.scala.strings.concatstrings |
| 2 | + |
| 3 | +import org.scalatest.flatspec.AnyFlatSpec |
| 4 | +import org.scalatest.matchers.should.Matchers |
| 5 | + |
| 6 | +class ConcatStringUnitTest extends AnyFlatSpec with Matchers { |
| 7 | + |
| 8 | + it should "concat strings using + operator" in { |
| 9 | + val str1 = "Hello" |
| 10 | + val str2 = "Baeldung" |
| 11 | + val combined = str1 + str2 |
| 12 | + combined shouldBe "HelloBaeldung" |
| 13 | + } |
| 14 | + |
| 15 | + it should "concat string with another type using + operator" in { |
| 16 | + val str1 = "Hello" |
| 17 | + val combined = str1 + 10 |
| 18 | + combined shouldBe "Hello10" |
| 19 | + } |
| 20 | + |
| 21 | + it should "concat strings using ++ operator" in { |
| 22 | + val str1 = "Hello" |
| 23 | + val str2 = "Baeldung" |
| 24 | + val combined = str1 ++ str2 |
| 25 | + combined shouldBe "HelloBaeldung" |
| 26 | + } |
| 27 | + |
| 28 | + it should "concat strings using concat" in { |
| 29 | + val str1 = "Hello" |
| 30 | + val str2 = "Baeldung" |
| 31 | + val combined = str1.concat(str2) |
| 32 | + combined shouldBe "HelloBaeldung" |
| 33 | + } |
| 34 | + |
| 35 | + it should "concat strings using string interpolation" in { |
| 36 | + val str1 = "Hello" |
| 37 | + val str2 = "Baeldung" |
| 38 | + val combined = s"$str1$str2" |
| 39 | + combined shouldBe "HelloBaeldung" |
| 40 | + } |
| 41 | + |
| 42 | + it should "concat strings using multi line string interpolation" in { |
| 43 | + val str1 = "Hello" |
| 44 | + val str2 = "Baeldung" |
| 45 | + val combined = s"""$str1$str2""" |
| 46 | + combined shouldBe "HelloBaeldung" |
| 47 | + } |
| 48 | + |
| 49 | + it should "concat strings using StringBuilder" in { |
| 50 | + val str1 = "Hello" |
| 51 | + val str2 = "Baeldung" |
| 52 | + val combined = new StringBuilder(str1).append(str2).toString() |
| 53 | + combined shouldBe "HelloBaeldung" |
| 54 | + } |
| 55 | + |
| 56 | + it should "concat strings using mkString" in { |
| 57 | + val strings = Seq("Hello", "Baeldung") |
| 58 | + val combined = strings.mkString |
| 59 | + combined shouldBe "HelloBaeldung" |
| 60 | + strings.mkString(",") shouldBe "Hello,Baeldung" |
| 61 | + } |
| 62 | + |
| 63 | + it should "concat strings using reduce" in { |
| 64 | + val strings = Seq("Hello", "Baeldung") |
| 65 | + val combined = strings.reduce(_ + _) |
| 66 | + combined shouldBe "HelloBaeldung" |
| 67 | + val combinedWithComma = strings.reduce((a, b) => (a + "," + b)) |
| 68 | + combinedWithComma shouldBe "Hello,Baeldung" |
| 69 | + } |
| 70 | + |
| 71 | + it should "concat strings using foldLeft" in { |
| 72 | + val strings = Seq("Hello", "Baeldung") |
| 73 | + val combined = strings.foldLeft("")(_ + _) |
| 74 | + combined shouldBe "HelloBaeldung" |
| 75 | + List.empty[String].foldLeft("")(_ + _) shouldBe "" |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments