Nicola Gallazzi
Nicola Gallazzi

Reputation: 8705

Converting "Yes" or "No" string to Boolean in Kotlin

I'm wondering if there's a more efficient way to convert a "yes/no"string to boolean in kotlin. My solution is defining an extension function on String class and do the yes no che in a when expression:

fun String.toBoolean(): Boolean {
    when (this.toUpperCase()) {
        "YES" -> return true
        "NO" -> return false
    }
    return false
}

Any other possible ways?

Upvotes: 1

Views: 3513

Answers (3)

Curtes Malteser
Curtes Malteser

Reputation: 63

I would go with the simplest version of the xtreme with something like this (I noticed it was added as a comment above too).

fun String.toBoolean() = when (this.toUpperCase(Locale.getDefault())) {
    "YES" -> true
    else -> false
}

Upvotes: 0

Todd
Todd

Reputation: 31670

If the default case is false this could be simplified:

fun String.toBoolean() = equals("YES", ignoreCase = true)

To simplify this we are depending on the fact that anything that isn't "yes" will be false. We also tell equals that we would like it to do a case insensitive check (that's the second parameter).

Upvotes: 7

cactustictacs
cactustictacs

Reputation: 19524

Todd has the elegant solution but I have the xtreme one

val yeses = setOf("yes", "Yes", "yEs", "yeS", "YEs", "YeS", "yES", "YES")
fun String.toBoolean() = this in yeses

if you want xtremely moderate performance gains you might do something silly like this!

Upvotes: 2

Related Questions