Typeless lambda expression

I understand the syntax of Java8 lambda expressions, but why does the following code work without a special declaration like x? Why is the "base" printed?

public class LambdaExpressions {

    interface Foo {
        void bar(Object o);
    }

    static void doo(Foo f) {
        f.bar("baz");
    }

    public static void main(String[] args) {

        doo( x -> {System.out.println(x);});
    }

}
+5
source share
4 answers

Since the interface is a standard functional interface

This is a functional interface because it contains only one abstract method. This method takes one parameter and returns the value [void]

(Overrated for this question)

A lambda expression x -> { System.out.println(x); }can be rewritten as an anonymous class.

new Foo() {
    @Override
    public void bar(Object x) {
        System.out.println(x);
    }
}

doo, f, f.bar("baz");, "baz" x, .

public static void main(String[] args) {
    Foo f = new Foo() {
        @Override
        public void bar(Object x) {
            System.out.println(x);
        }
    };

    f.bar("baz");
}
+6

x :

- , . : , , . .

Object, , Object. :

, (§15.27.3) , .

+3

, , Foo .

( ) . Java 8 .

+1

Java - ,

  • [: a → aa; () → ab; ]
  • [: (int a, int b) → a + b; (, ) → + ; ]
  • If we want to declare argument types, parentheses are required [for example: a → a * a; (int a) → a * a; ]
  • For one line of expression, curly braces are optional [for example: a → aa; a → {return aa}; ]
  • or a single line of expression, the return keyword is optional [example: a → aa; a → {return aa}; ]

There are more rules you can follow in the basics of lambda expressions in Java 8

0
source

Source: https://habr.com/ru/post/1658130/


All Articles