0

I'm a little bit confused about why there is no such thing like lambda overloading.
I know lambda expression work with @FunctionalInterface If you have two or more abstract method in interface then compiler can't decide what function to call when you are using a lambda expression, so it is necessary to have only one abstract method in the interface if you want to use a lambda expression. But what if you have two or more function with different arguments or a different type of arguments or return type than the compiler can easily decide what function to call.

For example:

 interface Foo{
     void show(String message);
     void count(int number);
 }

 // Calling with lambda (Syntax is not correct)
 x -> "Example Message";  // It should need to call void show();
 x -> 7; // It should need to call void count();

Why this kind of thing is not available in java. isn't it a good thing.

Azeem Haider
  • 1,443
  • 4
  • 23
  • 41
  • What would you expect `x -> "Example Message"` to perform then if I also add `void hide(String message)` to the existing interface? to `show` or to `hide`? – Naman Jan 17 '19 at 06:34

1 Answers1

4

You've considered one side of the problem - which method the lambda expression should correspond to. What you haven't considered is what happens to all other methods in the interface.

The language could be specified so that the lambda expression corresponds to one method, and all the others throw a RuntimeException - but that would rarely be useful. Consider how the Foo would be used. You'd end up with an object that you could only call some methods on, and you wouldn't even know which methods you could call safely.

If you know you're only going to call one method (e.g. count in your example), then that's one standalone piece of functionality, and can be encapsulated in an interface on its own - at which point existing lambda expression functionality is fine. If you don't know that you only want to use a single method, then your proposal won't help anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194