default methods + lambdas = less code

Bartek Lipinski
ProAndroidDev
Published in
2 min readSep 30, 2017

--

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:

You can’t replace it with lambda because the DebouncingOnClickListener is an abstract class and not an interface.

With Java 8 default method you can simply convert this abstract class to an interface. Here’s how:

  1. Change abstract class to interface (also convert abstract method doClick to an interface method)
  2. Change implementing View.OnClickListener to extending it (if you didn’t know that: yes, interfaces can extend each other)
  3. Override the onClick callback of View.OnClickListener with a default method
  4. Wrap enabled field in something — simple wrapper class Enabled in my example (more on that in a second)
  5. 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:

Now the DebouncingOnClickListener is an interface, so you can replace this with lambda.

If you enjoyed this post, please show your support! Clap, follow, comment, share.

This really means a lot!

--

--

android engineer @whatnot | ex @reddit | ex @getthefabulous | recovering feature creep 💉 | https://github.com/blipinsk