0
Runnable runnable = new Runnable() {
   @Override
   public void run() {
       throw new RuntimeException("You cannot Pass!");
   }
};

Lets say I have a runnable like the one mentioned above. IntelliJ reports that all anonymous classes can be replaced by lambdas as of Java 8.

Can somebody help me out with the correct syntax.

Function that needs to be called with the runnable as parameter:

public void intercept(Runnable runnable) { ... }

PS: As to why somebody would need a runnable like that is not the question here, thank you

Sourav 'Abhi' Mitra
  • 2,390
  • 16
  • 15
  • 1
    Your idea itself can change your code into your desired code, just click on the lightbulb idea shows you. – halil Feb 25 '17 at 10:07

2 Answers2

2

Lambdas can be used to define Runnable interfaces, so not much change is needed:

Runnable runnable = () -> {
   throw new RuntimeException("You cannot Pass!");
};

The () is syntax for declaring no parameters — Compare this with e.g. a list of two parameters for defining a BiFunction<String, Integer, String>:

BiFunction<String, Integer, String> fooBarConcatenator = (foo, bar) -> foo + bar;
Matt
  • 74,352
  • 26
  • 153
  • 180
errantlinguist
  • 3,658
  • 4
  • 18
  • 41
1

Runnable's method takes no argument,so the code is the following:

Runnable r = () -> { throw new RuntimeException(); };

However, note that you will not be able to throw a checked exception, because Runnable's run() has no defined checked exceptions to be thrown. To achieve that, you will have to define your own functional interface and define a lambda that wraps a Runnable. Check this for more.

Also, many of the modern IDEs (especially Intellij) provide you with hints that auto-replace substitutions like this. So, check on the left part of the screen for a little warning icon, which when clicked will replace automatically your code with the corresponding lambda expression. Alternatively, click Alt + Enter ( Cmd + Enter for Mac) in the specific line.

Community
  • 1
  • 1
Dimos
  • 8,330
  • 1
  • 38
  • 37