I couldn't find a better title for describing how can I avoid code duplication (require expressions) in this Kotlin class:
class Person(email: String) {
var email: String = email
set(value) {
require(value.trim().isNotEmpty(), { "The email cannot be blank" })
field = value
}
init {
require(email.trim().isNotEmpty(), { "The email cannot be blank" })
}
}
In java, I would have a setter with the name validation and then I would call it from the constructor.
What is the idiomatic way of doing that in Kotlin ?
You can do it just like in java. You just have to remove the primary constructor and make a secondary constructor instead. You will have to do the assignment manually though, like in java. So it would look like this: