2
import java.util.function.Function;

public interface Printable {
    public String print(String s);
    public static void main(String[] args) {
        Function<String, String> fn = p -> p +" from lambda";
        String result = fn.apply("test");
        System.out.println(result);
    }

}

What I mean is, fn.apply("test") seems unnecessary, since the only possible method is apply. So why not syntax like fn::(test) ?

4
  • 1
    Functional interfaces can have more than one method. They can only have a single abstract method (which is implemented by a lambda expression), but the interfaces can have additional default methods. There is nothing special about functional interfaces once the object exists and you're calling a method. Also, Java is historically averse to operator overloading.
    – amon
    Commented Jun 15 at 16:24
  • 1
    My speculation: Because doing so would require language and compiler changes the Java team found too complicated or annoying to implement. Java team could implement a () call on a delgate interface, like in C#, but it would most likely require non-trivial change to language's syntax and compiler implementation.
    – Euphoric
    Commented Jun 15 at 18:26
  • Why did you ask for fn::(test) and not for fn(test)?
    – Doc Brown
    Commented Jun 17 at 13:58
  • @DocBrown: yes, no need for the two colons. bottom line, it seems like something like i described could work and would be convenient.
    – releseabe
    Commented Jun 17 at 16:08

2 Answers 2

6

Why does a Java lambda need to explicitly mention the method of the functional interface?

Because this is Java.

the only possible method is apply.

Not true. And not the point. For fn::(test) to work you only need a method that defaults as that one. Not for it to be the only one.

So why not do that?

Because this is Java. Just because it’d be nice and make sense to us code users doesn’t mean we get it. This isn’t the first time we got excited over what we thought was going to be an exciting new language feature only to end up with syntactic sugar on an old work around. See type erasure.

It’s just Java being Java.

3

:: it is referred to be the double colon operator, it is used to refer methods, method reference being Java programming language implementation for passing methods among parameters when calling a method that require (a) Function argument(s), with emphasise on: to refer a method is different than to call a method.

This fn::(test) hypothetical syntax is a mixture between referring and calling the apply method of a Function. So the answer to...

So why not do that?

...is because :: is useful for something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.