Given:
class JWTToken(val token: String) {
// ...
var email: String = jwt.claims["email"]?.asString()?:
throw Exception("null email")
}
The exception is thrown if wt.claims["email"] is null, but not if the is string empty.
How can the check for the empty string be concisely added?
>Solution :
Kotlin’s require built-in would be a good candidate here:
val aNullableOrBlankValue: String? = "..."
class JWTToken(val token: String) {
var email: String = aNullableOrBlankValue
.let { requireNotNull(it) { "Email should not be null..." } }
.apply { require(isNotBlank()) { "Email should not be blank..." } }
}
The methods require and requireNotNull will throw an IllegalArgumentException if the value is false for require, or null for requireNotNull.
Another concise way to write this would be:
var email2: String = aNullableOrBlankValue
.apply { require(!isNullOrBlank()) { "Email should not be blank or null..." } }!!
Albeit less readable (notice the !!), and error not as clear.
Do note that isBlank is not the same as isEmpty and it really depends on your use-case. (In your case, isBlank is more appropriate as emails should not be blank)
isBlankchecks that a char sequence has a 0 length or that all indices are white space.isEmptyonly checks that the char sequence length is 0.
See: stackoverflow.com/a/45337014/5037430 for further detalis.