mikenlanggio
mikenlanggio

Reputation: 1137

What's syntax object : interface in Kotlin?

I'm newbie in Kotlin and Android.

I confused when see syntax when use TextWatcher like this:

editTextSample.addTextChangedListener(object : TextWatcher{
    override fun afterTextChanged(s: Editable) {}

    override fun beforeTextChanged(s: CharSequence, start: Int,
                                   count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence, start: Int,
                               before: Int, count: Int) {
        txtView1.setText("Text in EditText : "+s)
    }
})

Can you explain it for me. Thank you

Upvotes: 0

Views: 170

Answers (2)

Sebastian Pakieła
Sebastian Pakieła

Reputation: 3029

Notation object : TextWatcher is just creating an anonymous class here. It's just kotlin way of creating it. Kotlin gives you more methods to implement TextWatchers.

You can import androidx.core:core-ktx dependency which provides a lot of nice features. One of them is extensions for textwatchers. With using this you can simplify your code to:

        editTExt.doOnTextChanged { text, start, count, after -> 
            //Do something here
        }

Upvotes: 1

Makarand
Makarand

Reputation: 1123

EditText class extends TextView class which contains a method called addTextChangedListener().

Here you are creating the object of EditText class and calling that method. Where you need to pass the object of TextWatcher interface as argument.

[Hold on.. but we can not create the object of interface. So here we are using concept of anonymous class for that, check this ].

and as the interface contains three methods we have to override them all. That's it.

Upvotes: 1

Related Questions