如何在Kotlin类构造函数主体中使用自定义setter

7 kotlin

我找不到更好的标题来描述如何避免在此Kotlin类中进行代码重复(需要表达式):

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" })
    }
}
Run Code Online (Sandbox Code Playgroud)

在Java中,我将有一个带有名称验证的设置器,然后从构造函数中调用它。

在Kotlin中惯用的方式是什么?

Pau*_*cks 2

在构造函数外部定义成员,并从 init 块调用 setter:

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
    }
}
Run Code Online (Sandbox Code Playgroud)