CPA
CPA

Reputation: 3063

Serialize a map of lambda functions

I have Type2 extends Type1.

And I have a map of functions:

private final Map<String, Consumer<Type1>> functionMap;
{
        functionMap = new HashMap<>();    
        functionMap.put("test", (Type1 t) -> evalSessionSetupReq((Type2) t));
}

That works fine. But when I try to serialize that map, I get a NotSerializableException exception.

I tried to use:

functionMap.put("test", (Serializable)(Type1 t) -> evalSessionSetupReq((Type2) t));

But it doesn't work.

How can I serialize such a map of lambda functions?

Upvotes: 0

Views: 85

Answers (1)

marstran
marstran

Reputation: 28056

I think you can cast the lambda to the intersection of the functional interface and Serializable to make it serializable. Try this:

functionMap.put("test", 
      (Consumer<Type1> & Serializable)((Type1 t) -> evalSessionSetupReq((Type2) t)));

Upvotes: 2

Related Questions