如何覆盖kotlin中的setter方法?

时间:2017-06-29 03:34:30

标签: kotlin android-databinding

class loginViewModel(): BaseObservable() {

    var errorEmail:String?=null
    var errorPassword:String?=null

    var userEmailAddress:ObservableField<String> = ObservableField()
    var userPassword:ObservableField<String> = ObservableField()

    fun setUserEmailAddress(email:ObservableField<String>){
        this.userEmailAddress=email
        /* To get value of edittext enterd by user, This Updates the value of userEmail on Every LEtter Entered by User*/
        notifyPropertyChanged(R.id.email_address)
        notifyPropertyChanged(BR.errorEmail)
    }

}

但是得到了错误

Platform declaration clash: The following declarations have the same JVM signature (setUserEmailAddress(Landroid/databinding/ObservableField;)V):
  • public final fun setUserEmailAddress(email:ObservableField<String>): Unit
  • public final fun <setUserEmailAddress>(<set-?>:ObservableField<String>): Unit

我试过了this solution

kotlin version = 1.1.2-4 我试图改写我认为我们做不到的乐趣。

1 个答案:

答案 0 :(得分:3)

您可以为您的字段声明custom setter,而不是制作新的setUserEmailAddress()方法。您可以在下面看到执行此操作的代码。

您收到此错误的原因是因为在您创建var时会自动为您生成一个setter。您正在创建的setUserEmailAddress函数与其名称匹配,从而导致命名空间冲突。

class loginViewModel(): BaseObservable() {
    var errorEmail:String?=null
    var errorPassword:String?=null

    var userPassword:ObservableField<String> = ObservableField()
    var userEmailAddress:ObservableField<String> = ObservableField()
        set(email){ // the type of email is inferred
            field=email // we can access the backing field in our custom setter

            /* To get value of edittext enterd by user,
               This Updates the value of userEmail on 
               Every LEtter Entered by User*/
            notifyPropertyChanged(R.id.email_address)
            notifyPropertyChanged(BR.errorEmail)
        }
}