Scala Convert String to Boolean

1. Introduction

Converting a string to a boolean is a common task in many programming scenarios. In Scala, this can be achieved through several approaches. This blog post will discuss how to convert a string to a boolean in Scala, covering different methods and their respective use cases.

2. Program Steps

1. Define strings that represent boolean values.

2. Demonstrate various methods to convert these strings to booleans, including manual comparison and using built-in methods.

3. Print the results to verify the conversion.

4. Execute the code to see how each method works.

3. Code Program

object StringToBooleanDemo extends App {
  val trueString = "true"
  val falseString = "false"

  // Method 1: Direct Comparison
  val booleanValue1 = trueString.equalsIgnoreCase("true")
  println(s"Direct comparison (trueString): $booleanValue1")

  val booleanValue2 = falseString.equalsIgnoreCase("true")
  println(s"Direct comparison (falseString): $booleanValue2")

  // Method 2: Using toBoolean
  val booleanValue3 = trueString.toBoolean
  println(s"Using toBoolean (trueString): $booleanValue3")

  val booleanValue4 = falseString.toBoolean
  println(s"Using toBoolean (falseString): $booleanValue4")

  // Method 3: Using a match expression
  def stringToBoolean(s: String): Boolean = s.toLowerCase match {
    case "true" => true
    case "false" => false
    case _ => throw new IllegalArgumentException("Invalid boolean string")
  }

  println(s"Using match (trueString): ${stringToBoolean(trueString)}")
  println(s"Using match (falseString): ${stringToBoolean(falseString)}")
}

Output:

Direct comparison (trueString): true
Direct comparison (falseString): false
Using toBoolean (trueString): true
Using toBoolean (falseString): false
Using match (trueString): true
Using match (falseString): false

Explanation:

1. The first method uses equalsIgnoreCase to compare the string directly with "true". This method is case-insensitive.

2. toBoolean is a Scala method that converts a string to a boolean. It returns true if the string is "true" (case-insensitive), otherwise false.

3. The match expression method provides a more robust way to convert strings to booleans. It can handle invalid inputs explicitly and throw an exception if the string does not represent a boolean value.


Comments