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

我找不到更好的标题来描述如何避免在这个Kotlin类中的代码重复(需要expression式):

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中做这些事的惯用方法是什么?

使用委托。 有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 } } 

定义构造函数外的成员,并从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 } } 

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