How to use a custom setter in the Kotlin class constructor case

I could not find a better heading to describe how I can avoid code duplication (expression required) 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 will have a setter with name verification, and then I would call it from the constructor.

What is the idiomatic way to do this in Kotlin?

+4
source share
3 answers

Use a delegate. There is an observable () delegate that already exists.

class Person(initialEmail: String) { // No "var" any more.
    var email: String by Delegates.observable("") {
    _, _, newValue ->
        // This code is called every time the property is set.
        require(newValue.trim().isNotEmpty(), { "The email cannot be blank" })
    }

    init {
        // Set the property at construct time, to invoke the delegate.
        email = initialEmail
    }
}
+3
source

Define the element outside the constructor and call the installer from the init block:

class Person(initialEmail: String) { // This is just the constructor parameter.
    var email: String = "" // This is the member declaration which calls the custom setter.
        set(value) {          // This is the custom setter.
            require(value.trim().isNotEmpty(), { "The email cannot be blank" })
            field = value
        }

    init {
        // Set the property at construct time, to invoke the custom setter.
        email = initialEmail
    }
}
+2
source

, java. . , , java. , :

class Person {
    constructor(email: String) {
        this.email = email
    }

    var email: String
        set(value) {
            require(value.trim().isNotEmpty(), { "The email cannot be blank" })
            field = value
        }
}
+1

Source: https://habr.com/ru/post/1689543/


All Articles