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?

2
  • 1
    view.findViewById<EditText>(R.id.some_edit_text).filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend -> {// TODO: Do something "" } }) Is this what are you looking for? Commented Oct 5, 2018 at 19:27
  • 1
    You can press Alt + Enter to have Android Studio automatically convert most lambdas for you, FYI Commented Oct 5, 2018 at 19:41

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.