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

时间:2017-11-19 23:58:57

标签: 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" })
    }
}

在java中,我会有一个名为validation的setter,然后我会从构造函数中调用它。

在Kotlin中这样做的惯用方法是什么?

4 个答案:

答案 0 :(得分:3)

使用代表。已经存在的observable()委托。

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
    }
}

答案 1 :(得分: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
    }
}

答案 2 :(得分:1)

你可以像在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
        }
}

答案 3 :(得分:0)

有另一种方法,使用伴生对象并在那里创建对象,它有点像构造函数,并以不同的方式满足您的要求。

data class Target(
        val date: LocalDate,
        val id: Long,
        val stringId: String,
) {
    companion object {
        fun create(date: LocalDate, id: Long, stringId: String?,): Target{
            val nonNullStringId= if (stringId.isNullOrEmpty()) "" else stringId
            return Target(date, id, nonNullStringId)
        }
    }
}