Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate class String property is not empty in Kotlin?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading