Kotlin字符串.toBoolean替代方法

4
自从Kotlin 1.4版本以后,String.toBoolean()方法被弃用而没有提供替代方法。现在我们应该使用java.lang.Boolean.parseBoolean方法吗?或者Kotlin有其他替代方案吗?
/**
 * Returns `true` if the content of this string is equal to the word "true", ignoring case, and `false` otherwise.
 */
@Deprecated("Use Kotlin compiler 1.4 to avoid deprecation warning.")
@DeprecatedSinceKotlin(hiddenSince = "1.4")
@kotlin.internal.InlineOnly
public actual inline fun String.toBoolean(): Boolean = this.toBoolean()

/**
 * Returns `true` if this string is not `null` and its content is equal to the word "true", ignoring case, and `false` otherwise.
 */
@JvmName("toBooleanNullable")
@SinceKotlin("1.4")
@kotlin.internal.InlineOnly
public actual inline fun String?.toBoolean(): Boolean = java.lang.Boolean.parseBoolean(this)
4个回答

5

正如您在问题中展示的那样,现在有String?.toBoolean()。它类似但也可以用于null引用,在这种情况下它将返回false


1
我应该更仔细地阅读弃用警告。我的Intellij使用的是Kotlin编译器1.3.72,而不是1.4,因为IDE中过时的Kotlin插件,但我的gradle配置是正确的,所以只有我的编辑器显示了弃用警告。更新Intellij Kotlin插件解决了问题。

好的,所以你现在有效地使用了 String?.toBoolean(),应该按照我在答案中提到的方式使用。 - herman

0
在我的情况下,这也是一个IDE问题,但插件已经是最新的了。所以简单地重新启动解决了这个问题。

0

IntelliJ和Android Studio使用自己的Kotlin编译器,特别是用于lint检查。因此,即使在您的构建脚本中已经使用了Kotlin 1.4++,您仍会收到“使用Kotlin编译器1.4以避免弃用警告”的提示。

// Top-level build file
buildscript {

    // IntelliJ/Android studio don't use this Kotlin version for lint check.
    ext.kotlin_version = "1.4.10"

    repositories {
        google()
        jcenter()
    }

你需要在设置中更改编译器。偏好设置 -> 语言和框架 -> Kotlin,更新Kotlin编译器版本。

preference


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接