In Scala, how to serialize a single abstract method interface that carries an outer object that cannot be serialized?

37 Views Asked by At

In Scala 2/3, if a trait is defined with a single abstract method:

  trait In
  trait Out

  trait FnBase {

    def apply(arg: In): Out
  }

any function with identical in/out signature will be coerced into an ad-hoc class that inherit this trait, this coercion has higher priority than any implicit conversion, e.g.:

trait NonSerializable {
  val v1 : FnBase = _ => new Out {}
// automatically becomes
  val v2 : FnBase = new FnBase {def apply(v: In): Out = new Out {}}
}

This is problematic as the serialized form of v2 will now carry NonSerializable as an outer reference, and trigger a NotSerializableException when being serialized.

This behaviour cannot be changed because:

  • single abstract method interface already has the highest priority
  • outer reference cannot be marked as @transient, and will always be included in serialized form

I'd like to disable this behaviour, what's the easiest way to do so?

0

There are 0 best solutions below