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?

asked Jul 13, 2021 at 8:52
7
  • It's Object, essentially. There's no other common supertype between A and B. Commented Jul 13, 2021 at 8:54
  • Perhaps you are looking for an explanation of IntersectionType? Commented Jul 13, 2021 at 8:56
  • 1
    See also stackoverflow.com/questions/60148411/… Commented Jul 13, 2021 at 8: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. Commented Jul 13, 2021 at 9:00
  • 1
    @marstran didn't know that. Thanks for clarifying. Commented Jul 13, 2021 at 9:05

1 Answer 1

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$$Lambda1ドル/1642360923@1376c05c

answered Jul 13, 2021 at 9:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.