android 随机布尔值,android - Java Boolean.valueOf() equivalent in Kotlin? - Stack Overflow
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)
更多推荐


所有评论(0)