0

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?

1 Answer 1

2

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)

isBlank checks that a char sequence has a 0 length or that all indices are white space. isEmpty only checks that the char sequence length is 0.

See: stackoverflow.com/a/45337014/5037430 for further detalis.

Sign up to request clarification or add additional context in comments.

6 Comments

You don't need !! because isNullOrBlank has a contract that causes it to be smart cast to not-null.
Hmm for which Kotlin version? It seems that the apply scoped function negate the smart cast? (Jetbrains IDE complaining) Perhaps my IDE config is messed up.
Oh, you're right. I guess smart casting doesn't work in that case. If you use .let { require(!it.isNullOrBlank(); it }, then it allows it. I guess since the return type is already determined before the code inside the apply/let lambda, the contract doesn't help narrow it down.
Ah I see, cool, thanks for that! (Always wondered why it doesn't smart cast there)
Looks like this might be fixed in Kotlin 2.0: youtrack.jetbrains.com/issue/KT-28806 This is subtly different, since it's about the smart cast working internally in the lambda, but I think it might also apply. But this more applicable YouTrack issue has not been updated, so I'm not sure. youtrack.jetbrains.com/issue/KT-48894/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.