Limit the number of characters of a String parameter in Kotlin

Viewed 34

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!" }
}
1 Answers

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.

Related