The following code produces false regardless of whether I have 0 or 1 as an input.
fun main() {
val num: String = readln().toString()
val b: Boolean = num.toBoolean()
println(b)
}
I wanted to convert 0 to false and 1 to true.
The following code produces false regardless of whether I have 0 or 1 as an input.
fun main() {
val num: String = readln().toString()
val b: Boolean = num.toBoolean()
println(b)
}
I wanted to convert 0 to false and 1 to true.
In Kotlin, numbers are not associated to booleans like in other languages. The convention 0=false and 1=true is not really present in the language or stdlib, so it's unlikely you'll find anything that does it out of the box.
If you really do want to support this case, you'll have to implement it yourself. One way to do it is like this:
fun main() {
val num = readln()
val b = num.zeroOrOneToBoolean()
println(b)
}
private fun String.zeroOrOneToBoolean(): Boolean = when(num) {
"0" -> false
"1" -> true
else -> throw IllegalArgumentException("$this cannot be converted to boolean, expected 0 or 1")
}
You could also choose to consider other things as true or false:
private fun String.toBooleanLenient(): Boolean = when(num) {
"0", "false", "False" -> false
"1", "true", "True" -> true
else -> throw IllegalArgumentException("$this cannot be converted to boolean")
}
Or you could decide that you want anything that is not "1" to be false, in which case you can really simply just use ==:
fun main() {
val num = readln()
val b = num == "1" // true for the string "1", false for everything else
println(b)
}