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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值