How to use custom setter in Kotlin class constructor body

No, because in that case it would still be duplicated code. If this is a pattern that you find yourself to be repeating regularly, than property delegation is probably a better choice.

Your fields would look like this:

var email: String by Required("The email cannot be blank")

You would need to implement the Required delegation. See for example https://kotlinlang.org/docs/reference/delegated-properties.html

Note also that there might be an implementation of such a property delegation in the standard lib already. In that case you don’t need to implement it yourself.

3 Likes