R
R
Rarity72020-01-28 18:09:47
Android
Rarity7, 2020-01-28 18:09:47

What is the difference between creating a TextWatcher in Android on Kotlin?

What is the difference between the two ways to create a TextWatcher
1st way

val textChangedListener = object: TextWatcher{

        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            
        }

    }


2nd way
private object textChangedListener: TextWatcher{

        override fun afterTextChanged(p0: Editable?) {
        }

        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

        }

    }

And in the 1st and 2nd ways, I can create a TextChangedListener, but I can't figure out which one is correct and what's the difference.

And by the way, in the 2nd way, I can't call the functions of the outer class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-01-28
@Rarity7

Correct first. The word object has different meanings. In the first case, you create an object of an anonymous class that implements the listener. In the second case, you create a singleton textChangedListener of type textChangedListener (i.e. the names of the class and its only instance are the same. By the way, this is why singleton objects are usually named with a capital letter.). In the second case, of course, you cannot call other methods, because object is not an inner class. Thus, it is little more than completely useless.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question