Cristan
Cristan

Reputation: 14085

Limit the number of characters of a String parameter in Kotlin

I have a method which accepts a String as an argument. How can I indicate that this parameter can only have an X amount of characters?

fun logEvent(name: String) {
    require(name.length <= 40) { "Event name $name is too long!" }
}

Upvotes: 1

Views: 1908

Answers (1)

Cristan
Cristan

Reputation: 14085

Use the Size annotation of androidx.annotation:

fun logEvent(@Size(max = 40) name: String)
    require(name.length <= 40) { "Event name $name is too long!" }
}

You can set min, max, multiple and value (with which you can specify a specific length). This will trigger a nice warning in your IDE when appropriate. It's just a warning though: the code will still run and accept Strings of any size.

Upvotes: 3

Related Questions