Java Boolean.valueOf() equivalent in Kotlin?
It is, as already mentioned, .toBoolean()
.
It works pretty simple: if the value of a String is true
, ignoring case, the returning value is true
. In any other case, it's false. Which means, if the string isn't a boolean, it will return false.
Kotlin essentially has two variations of types: Any
and Any?
. Any
can of course be absolutely any class, or referring to the actual class Any
.
toBoolean
requires a String
, which means a non-null String. It's pretty basic:
val someString = "true"
val parsedBool = someString.toBoolean()
It gets slightly more complicated if you have nullable types. As I mentioned, toBoolean
requires a String
. A String?
!= String
in these cases.
So, if you have a nullable type, you can use the safe call and elvis operator
val someString: String? = TODO()
val parsedBool = someString?.toBoolean() ?: false
Or, if you can live with a nullable boolean, you don't need the elvis operator. But if the String is null, so will the boolean be.
Just an explanation of the above:
someString?.//If something != null
toBoolean() // Call toBoolean
?: false // Else, use false
Also, you can't compile a program that uses toBoolean
on a nullable reference. The compiler blocks it.
And finally, for reference, the method declaration:
/**
* Returns `true` if the contents of this string is equal to the word "true", ignoring case, and `false` otherwise.
*/
@kotlin.internal.InlineOnly
public actual inline fun String.toBoolean(): Boolean = java.lang.Boolean.parseBoolean(this)
You should know if it is null
before the call, because you are either dealing with a String
or a String?
. ?
is the suffix that Kotlin uses to designate nullable types.
If you have a String
, then you should be able to use toBoolean()
.
If you have a String?
— and so you may have a value or you may have null
— you could use a null-safe call plus the Elvis operator to specify what value you want if the String?
is null
:
val foo: String? = "true"
val bar: String? = null
println(foo?.toBoolean())
println(bar?.toBoolean() ?: false)
This prints:
true
false
bar?.toBoolean()
evaluates to null
, and null ?: false
evaluates to false
.
String.toBoolean
Returns true if the contents of this string is equal to the word "true", ignoring case, and false otherwise.
In Kotlin, a String is never null, so you don't have to check it. This returns a Boolean (true only if string value is 'true')
myString.toBoolean()
Now if you have a String? type and want a Boolean
myString?.toBoolean() ?: false
If you are ok with a Boolean? type returned
myString?.toBoolean()