0

In the following code:

interface Callback {
    void greet(String greeting);
}

private static <T extends Callback & Serializable> void greetMe(T callback) {
    callback.greet("Hello world!");
}

public static void main(String[] args) {
    greetMe(greeting -> System.out.println(greeting));
}

The following line does not compile, because the lambda is not Serializable:

greetMe(greeting -> System.out.println(greeting));

My question is, is there any syntactic sugar for making the lambda implement Serializable, or do I have to make it a non-anonymous class?

DonAlonzo
  • 77
  • 1
  • 6

1 Answers1

1

From the JLS 15.16. Cast Expressions:

Casts can be used to explicitly "tag" a lambda expression or a method reference expression with a particular target type. To provide an appropriate degree of flexibility, the target type may be a list of types denoting an intersection type, provided the intersection induces a functional interface (§9.8).

You can cast it directly to Serializable:

greetMe((Callback & Serializable) greeting -> System.out.println(greeting));
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Roland
  • 22,259
  • 4
  • 57
  • 84
  • 1
    There are a lot of topics dealing with this subject, please flag as duplicate instead of answering. – Mistalis Apr 04 '17 at 09:00
  • 1
    you are right... usually I do mark them or vote it to be a duplicate... it just happened that I had the answer already and so the further research of whether it was even asked was done after that... and all that just happened within 7 minutes ;-) – Roland Apr 04 '17 at 09:17