1. Introduction

When working with Strings in Scala, we might encounter scenarios where we need to check if all the characters in a String are either uppercase or lowercase.

In this tutorial, let’s discuss various ways to achieve this in Scala.

2. Understanding the Problem

Before getting started with the implementation, let’s clearly define the problem with some sample data:

val allUpper = "BAELDUNG @ 2024"
val allLower = "baeldung @ 2024"
val mixed = "Baeldung @ 2024"

Our implementation should return true when we pass the allUpper or allLower variables. Conversely, it should return false for the mixed variable. It’s important to note that the special characters within the strings are treated equivalently as both uppercase and lowercase characters, ensuring they don’t affect the overall outcome of the evaluation.

3. Converting and Comparing

The String class offers the methods toUpperCase() and toLowerCase() to convert a String to uppercase and lowercase, respectively. By converting a String and comparing it to the original, we can check if all the characters are either uppercase or lowercase.

Let’s look at the implementation:

def convertAndCheck(str: String): Boolean = {
  str.toUpperCase == str || str.toLowerCase == str
}

If either condition is satisfied, the method returns true.

4. Using forall()

Alternatively, instead of converting the entire String and comparing, we can check each character to see if it’s uppercase or lowercase and use forall() to ensure this is satisfied for all characters.

Let’s look at the implementation:

def isUpperLowerAndForAll(str: String): Boolean = {
  val filteredStr = str.filter(_.isLetter)
  filteredStr.forall(_.isUpper) || filteredStr.forall(_.isLower)
}

Here, we utilized the forall() function with isUpper() and isLower() checks on each character. However, before doing that, we eliminated all the special characters from the String.

5. Using Regular Expression

Another approach to performing this check is to use regular expressions.

Let’s look at the implementation:

def regexCheck(str: String): Boolean = {
  val filteredStr = str.filter(_.isLetter)
  filteredStr.matches("^[A-Z]*$") || filteredStr.matches("^[a-z]*$")
}

After filtering out only alphabetic characters, we utilize regular expressions to verify uppercase and lowercase conditions.

6. Using count()

Let’s explore another method to verify whether all characters in a string are exclusively uppercase or lowercase:

def countAndCheck(str: String): Boolean = {
  val filteredStr = str.filter(_.isLetter)
  filteredStr.count(_.isUpper) == 0 || filteredStr.count(_.isLower) == 0
}

Similar to our previous approach, we first filtered out non-alphabetic characters. Next, we utilized the count() method to count the occurrences of uppercase and lowercase characters. If either count is zero, it confirms uniformity in the case throughout all alphabetic characters.

7. Testing the Implementations

Now that we’ve implemented several methods to ensure the uniform case of a String, it’s important to write tests to validate the accuracy of our implementations. We can utilize ScalaTest for writing unit tests. Additionally, we can leverage parameterized tests with the TableDrivenPropertyChecks trait from ScalaTest to minimize boilerplate code.

Let’s write unit tests for all the implementations together:

private val fns = Seq(convertAndCheck, isUpperLowerAndForAll, regexCheck, countAndCheck)
private val table = Table(
  ("Input", "Expected Result"),
  ("BAELDUNG @ 2024", true),
  ("baeldung @ 2024", true),
  ("Baeldung @ 2024", false),
  ("2024 @@@ ", true),
  ("          ", true)
)
it should "check if all characters are upper or lower" in {
  fns foreach { fn =>
    forAll(table) { (input, expected) =>
      withClue("for string: " + input) {
        fn(input) shouldBe expected
      }
    }
  }
}

First, we included all the functions to be tested in a Seq. Following this, we constructed a table outlining different inputs and their respective expected outputs. Using the forAll() function, we tested each implementation against all inputs in the table.

8. Conclusion

In this tutorial, we explored different methods to verify whether a String exclusively contains uppercase or lowercase characters. Additionally, we covered these implementations using various test data with parameterized tests to ensure accuracy. Depending on specific requirements and preferences, we can select one of these methods to perform this validation.

As always, the sample code used in this article is available over on GitHub.