scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Lambda serialization fails for SAM types when abstract method is defined in trait/interface #12774

Closed RustedBones closed 11 months ago

RustedBones commented 1 year ago

Reproduction steps

Scala version: 2.12.17, 2.13.10 (works with scala 3.2.1)

Let's consider the following code

trait SerializableBiFunction[T, U, R] extends java.util.function.BiFunction[T, U, R] with Serializable

val fn: SerializableBiFunction[String, Int, Boolean] = (str, expected) => str.length == expected

val buffer = new ByteArrayOutputStream
val out = new ObjectOutputStream(buffer)
out.writeObject(fn)
val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray))
val res = in.readObject.asInstanceOf[SerializableBiFunction[String, Int, Boolean]]
println(res("success", 7))

Problem

The execution fails with

[error] java.io.NotSerializableException: Non-serializable lambda

I would expect the SAM type to be serializable, like in java.

I noted that if we change the SerializableBiFunction definition to

trait SerializableBiFunction[T, U, R] extends java.util.function.BiFunction[T, U, R] with Serializable {
  def apply(t: T, u: U): R
}

The code executes as expected and returns true.

noresttherein commented 1 year ago

It bugs me in way I can't put to words that functions aren't serializable by default. In a FP language, they are very often class members, which prevents those classes from serialization. I do not understand why: if something shouldn't be Serializable, then a non Serializable object in function's closure will prevent serialization anyway.