3

I want to set a filter to an edit text view.

view.findViewById<EditText>(R.id.some_edit_text).filters = arrayOf(object : InputFilter {
        override fun filter(source: CharSequence?,
                            start: Int,
                            end: Int,
                            dest: Spanned?,
                            dstart: Int,
                            dend: Int): CharSequence {
            // TODO: Do something
            return "";
        }
    })

Anyways, Android Studio is showing me the following warning/suggestion for object : InputFilter.

Convert to Lambda
This inspection reports an anonymous object literal implementing a Java interface with a single abstract method that can be converted into a call with a lambda expression.

I know how to use lambda expressions for example to set on click listeners but how do I provide a single element array with implementing the interface with a lambda expression?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jason Saruulo
  • 1,837
  • 4
  • 21
  • 21
  • 1
    `view.findViewById(R.id.some_edit_text).filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend -> {// TODO: Do something "" } })` Is this what are you looking for? – Quantum_VC Oct 05 '18 at 19:27
  • 1
    You can press Alt + Enter to have Android Studio automatically convert most lambdas for you, FYI – Matt Oct 05 '18 at 19:41

1 Answers1

6

Single-method objects don't actually need to explicitly declare the names of the methods, because there is just one. Generally, if you have an interface with a single method, you can convert i.e. this:

object : SomeInterface {
    override fun someMethod(){
        TODO("Something");
    }
}

to the simpler:

SomeInterface { 
    TODO("Something");
}

If there are arguments, you add those like this:

SomeInterface { x, y, z ->

}

However, due to a bug this isn't possible for interfaces defined in Kotlin. If you try this for an interface in Kotlin, it won't compile.

Your interface is defined in Java, which means you can do:

view.findViewById<EditText>(R.id.some_edit_text).filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend ->
    // TODO: Do something
    "";
})

Also, whenever you get any kind of suggestions in IntelliJ or Android Studio, Alt+Enter with the default keybindings shows you suggestions for solutions.

enter image description here

Clicking enter will automatically convert it, and if you click the right arrow, you get more options (including fixing all the related problems in the file, suppressing it). This also applies to errors (though not all have automatic fixing), warnings, and other suggestions.

Zoe
  • 27,060
  • 21
  • 118
  • 148