How to convert string to boolean in Scala?

Member

by odessa , in category: Other , 2 years ago

How to convert string to boolean in Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lucile , 2 years ago

@odessa you can use toBoolean to convert any string to a boolean in Scala, I would recommend using Try() as well to prevent exceptions if it can not be converted to boolean type:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import scala.util.Try

object HelloWorld {
    def main(args: Array[String]) {
        val str = "true"
        // Output: true
        println(Try(str.toBoolean).getOrElse(false))
        
        val str2 = "false"
        // Output: false
        println(Try(str2.toBoolean).getOrElse(false))
    }
}
by faustino.sanford , 9 months ago

@odessa 

There is no direct conversion of a String to a Boolean in Scala. However, you can write a simple function that returns true if the string is "true" or "yes", and false otherwise.


Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def stringToBoolean(s: String): Boolean = s.toLowerCase match {
  case "true" | "yes" => true
  case _ => false
}

val str1 = "true"
val str2 = "false"
val str3 = "yes"
val str4 = "no"

println(stringToBoolean(str1)) // true
println(stringToBoolean(str2)) // false
println(stringToBoolean(str3)) // true
println(stringToBoolean(str4)) // false