Strict version of String.toBoolean() #KT-42071

This commit is contained in:
Abduqodiri Qurbonzoda
2021-03-05 09:57:54 +03:00
parent 5f4a4fd8ae
commit 09ad5ca602
9 changed files with 80 additions and 0 deletions
@@ -1430,4 +1430,36 @@ internal fun CharSequence?.contentEqualsImpl(other: CharSequence?): Boolean {
}
return true
}
/**
* Returns `true` if the content of this string is equal to the word "true", `false` if it is equal to "false",
* and throws an exception otherwise.
*
* There is also a lenient version of the function available on nullable String, [String?.toBoolean].
* Note that this function is case-sensitive.
*
* @sample samples.text.Strings.toBooleanStrict
*/
@SinceKotlin("1.5")
public fun String.toBooleanStrict(): Boolean = when (this) {
"true" -> true
"false" -> false
else -> throw IllegalArgumentException("The string doesn't represent a boolean value: $this")
}
/**
* Returns `true` if the content of this string is equal to the word "true", `false` if it is equal to "false",
* and `null` otherwise.
*
* There is also a lenient version of the function available on nullable String, [String?.toBoolean].
* Note that this function is case-sensitive.
*
* @sample samples.text.Strings.toBooleanStrictOrNull
*/
@SinceKotlin("1.5")
public fun String.toBooleanStrictOrNull(): Boolean? = when (this) {
"true" -> true
"false" -> false
else -> null
}