Kotlin String.toBoolean replacement

Viewed 3367

Since Kotlin 1.4 String.toBoolean() is deprecated without documenting a replacement. Should we now use java.lang.Boolean.parseBoolean instead or is there a Kotlin way for replacing this?

/**
 * 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 Answers

As you show in the question, there is now String?.toBoolean(). It's similar but can also be called on null references, in which case it will return false.

I should have read the deprecation more carefully. My Intellij was using a Kotlin compiler 1.3.72 not 1.4 because of an outdated Kotlin Plugin in the IDE but my gradle configuration was correct, so only my editor showed the deprecation warning. Updating the Intellij Kotlin plugin fixed the problem.

In my case it was also an IDE problem but Plugins were already up to date. So simply a restart solved this for me.

IntelliJ and Android Studio use their own Kotlin compiler, especially for lint check. So, even though in your build script you already use Kotlin 1.4++, you'll get "Use Kotlin compiler 1.4 to avoid deprecation warning."

// 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()
    }

You need to change the compiler in the setting. Preferences -> Language & Frameworks -> Kotlin, update the Kotlin compiler version.

preference

Related