0

IntelliJ IDEA suggests that a runnable of the Form

findViewById(R.id.my_view).post(new Runnable() {
    @Override
    public void run() {
      Log.d("myTag", "hey");
    }
  });

is replaced with

findViewById(R.id.my_view).post(() -> Log.d("myTag", "hey"));

This Q&A covers the How.
But why is the latter preferable?

lucidbrot
  • 5,378
  • 3
  • 39
  • 68
  • 2
    It is definitely shorter and easier to read. – Henry Jan 31 '19 at 07:44
  • 2
    Interesting to read: https://stackoverflow.com/questions/22637900/java8-lambdas-vs-anonymous-classes – ernest_k Jan 31 '19 at 07:46
  • Related: [Lambda vs inner class loading performance](https://stackoverflow.com/questions/24764118/lambda-vs-anonymous-inner-class-performance-reducing-the-load-on-the-classloade) – lucidbrot Jan 31 '19 at 07:51

3 Answers3

3

A lambda expression creates a different bytecode that can be lighter. When using an anonymous class you tell the compiler to create an additional class only to later be instantiated and called.

When a lambda expression is used you tell the compiler to either create an object or a synthetic method. In the case of local variables being used the compiler will create an object and pass the captured variables to its constructor, essentially copying the reference. If no variables were captured it simply creates a private static method.

Additionally you can argue that lambdas look more readable.

Minn
  • 5,688
  • 2
  • 15
  • 42
1

This is how the java develops. Introducing lambdas in java 8 made code cleaner and less verbose. Just count the lines of code in

  @Override
    public void run() {
      Log.d("myTag", "hey");
    }
  });

and

findViewById(R.id.my_view).post(() -> Log.d("myTag", "hey"));

The whole method is just in one line of code. And the output of the code will be the same as in longer code. You can take a look at Scala, it's very common in Scala to write lambdas, and such short code.

Artem Vlasenko
  • 115
  • 1
  • 1
  • 7
0

People answered on "But why is the latter preferable?", but I will answer on

"Why does IntelliJ suggest to replace anonymous Runnables with Lambda Expressions?"

is that Intellij is checking the project level language that you've set and tries to suggest the way you should code using that version of the language. You most probably have it set to 8 or above.

In order to change it, go to Project structure (CTRL+ALT+SHIFT+S) -> Project and change the Project level language to be lower than 8.

Or if you only need it for specific module, go in Project structure again, and on Modules, click the module you need and from Sources tab, there's a Language level.

Edit: Also, take a look at this thread What is Project Language level in IntelliJ IDEA?

Chris
  • 165
  • 3
  • 12