Sobes.tech
Junior — Middle

How can you replace creating an anonymous class with using a lambda expression?

sobes.tech AI

Answer from AI

In Android (Java 8+), anonymous classes implementing functional interfaces (interfaces with a single method) can be replaced with lambda expressions to simplify and improve code readability.

For example, instead of such an anonymous class:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // action on click
    }
});

You can write a lambda:

button.setOnClickListener(v -> {
    // action on click
});

A lambda expression reduces syntax by eliminating the need to explicitly write the interface name and method, if the interface is functional. This makes the code shorter and clearer.

How can you replace creating an anonymous class with… - sobes.tech