default methods + lambdas = less code
This unusual combo of two Java 8 features is a great way to clean some of your Android code. The great thing about it, is that you can use this trick for all Android SDKs. There are no limitations.
It works for simple abstract
classes with a single abstract
method that you would use to create Anonymous classes in your code.
See how you could apply that toDebouncingOnClickListener
from Jake Wharton’s Butterknife.
The way you would use it in your code (even using Java 8), would be:
With Java 8 default
method you can simply convert this abstract class to an interface. Here’s how:
- Change
abstract class
tointerface
(also convertabstract
methoddoClick
to an interface method) - Change implementing
View.OnClickListener
to extending it (if you didn’t know that: yes, interfaces can extend each other) Override
theonClick
callback ofView.OnClickListener
with adefault
method- Wrap
enabled
field in something — simple wrapper classEnabled
in my example (more on that in a second) - BONUS: use the Java 8 lambda feature to simplify
ENABLE_AGAIN
The one important thing to remember is that interface
fields in Java 8 are not onlystatic
, but also final
. That means you cannot reassign this field (like it was done for enabled
in abstract class
version of DebouncingOnClickListener
). In the interface you have to (somehow) overcome this “limitation”. E.g. just like I did it in the example: wrap enabled
in a simple wrapper class Enabled
. This way you will not change the final Enabled
field, you will just change the boolean
value it wraps.
As a result of this conversion, not only your DebouncingOnClickListener
gets simpler, but you can simplify every single of your DebouncingOnClickListener
anonymous creations to: