Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Android] Retrolambda: What it is, how it works, and why should we use it
#1
What is it? How does it work?

In Java 8, Oracle introduced lambdas. These lambdas are implemented as nameless anonymous classes, a feature that has been in Java for ages. Retrolambda is a compile time library that utilizes JDK 8 to convert classes that use lambdas to use normal anonymous classes.

Why should we use it?

Consider this example copied from port/android-agera:

With Retrolambda:
Code:
Collections.sort(games, (a, b) -> a.name.compareTo(b.name));

Without Retrolambda:
Code:
Collections.sort(games, new Comparator<Game>() {
   @Override
   public int compare(Game a, Game b) {
       return a.name.compareTo(b.name);
   }
});

Java 8 lambdas also allow you to bind methods into lambdas (as long as the method signature matches the interface):

Code:
handler.postDelayed(this::hideToolbar, 1000);

vs.

Code:
handler.postDelayed(new Runnable() {
   @Override
   public void run() {
       hideToolbar();
   }
}, 1000);

Compile time costs:
None, the process of converting Java 8 to Java 7 is extremely fast.

Who uses it?

According to GitHub, Retrolambda is used in 4,160 projects (judging from the number of Gradle files that include it). It could be used in even more places, since this is a compile time dependency.
Reply

#2
I'm a bit wary about adding something that makes the compilation need a higher JDK than it would otherwise need, and then use an additional compilation step to turn it back down. I know there's a Gradle build step that does it for you, and it definitely is convenient from a code-perspective. Does RetroLambda actually get built into it at all (i.e. do you import the package anywhere in the code, or does JDK 8 just handle it?), or is it just a build step?
Reply

#3
(05-17-2016, 09:02 PM)endrift Wrote: I'm a bit wary about adding something that makes the compilation need a higher JDK than it would otherwise need, and then use an additional compilation step to turn it back down. I know there's a Gradle build step that does it for you, and it definitely is convenient from a code-perspective. Does RetroLambda actually get built into it at all (i.e. do you import the package anywhere in the code, or does JDK 8 just handle it?), or is it just a build step?

It's just a build step
Reply

#4
Alright, that sounds like a decent thing to use. I'm a big fan of lambdas, and anonymous classes in Java are a huge pain.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Powered By MyBB, © 2002-2024 Melroy van den Berg.