Ankur_009
Ankur_009

Reputation: 3730

How to override setter method in kotlin?

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

}

But getting the error

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

I tried this solution.

kotlin version = 1.1.2-4 I have tried to override the fun also which I think we can't.

Upvotes: 0

Views: 1868

Answers (1)

Dr. Nitpick
Dr. Nitpick

Reputation: 1712

You can declare a custom setter for your field instead of making a new setUserEmailAddress() method. You can see the code to do this below.

The reason you are getting this error is because there is a setter automatically generated for you when you make a var. The setUserEmailAddress function you are making matches its name causing a namespace clash.

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

Upvotes: 4

Related Questions