1

I can't understand what is it??

interface A{
    void foo();
}
interface B{
    void foo();
}

then what is the result of (A & B)

        System.out.println((A & B) () -> {
            System.out.println("1");
            System.out.println("2");
        });

Could someone help me?

treeliked
  • 383
  • 1
  • 4
  • 15
  • It's `Object`, essentially. There's no other common supertype between `A` and `B`. – ernest_k Jul 13 '21 at 08:54
  • Perhaps you are looking for an explanation of [IntersectionType](https://docs.oracle.com/javase/8/docs/api/javax/lang/model/type/IntersectionType.html)? – Hulk Jul 13 '21 at 08:56
  • 1
    See also https://stackoverflow.com/questions/60148411/expressing-anonymous-intersection-types-in-java – Hulk Jul 13 '21 at 08:58
  • 3
    @FedericoklezCulloca It's not a syntax error. The type `A & B` is an intersection type that also happens to be a functional "interface" because `A` and `B`'s `foo`-method has the same signature. The `System.out.println` will just print the `toString` of the lambda-object that is created. – marstran Jul 13 '21 at 09:00
  • 1
    @marstran didn't know that. Thanks for clarifying. – Federico klez Culloca Jul 13 '21 at 09:05
  • Indeed [no syntax error here](https://ideone.com/M0DGXC). – MC Emperor Jul 13 '21 at 09:08
  • Poor title. Rewrite to summarize your specific technical issue. – Basil Bourque Jul 13 '21 at 15:46

1 Answers1

4

A & B is an intersection type. An object of this type can act as both an A and as a B.

This particular intersection type also happens to be a "functional interface" type, which means that it only has 1 abstract method. This lets you instantiate an object of this type using a lambda-expression. A & B is a "functional interface" type because both A and B have the foo-method with the exact same type signature.

So that is what this code means. You are instantiating an object of type A & B, implementing the foo-method with the lambda-function.

(A & B) () -> {
  System.out.println("1");
  System.out.println("2");
}

The System.out.println will just print out this lambda object using it's toString-method. Note that it will not call the actual foo-method. Your code will therefore just print out something similar to this: Main$$Lambda$1/1642360923@1376c05c

marstran
  • 26,413
  • 5
  • 61
  • 67