From e077c24525bf8f9bd8b73684e630eb7fc6bcb5f6 Mon Sep 17 00:00:00 2001 From: Jason Zaugg Date: Thu, 14 Apr 2016 14:00:33 +1000 Subject: SI-9390 Emit local defs that don't capture this as static This avoids unnecessary memory retention, and allows lambdas that call the local methods to be serializable, regardless of whether or not the enclosing class is serializable. The second point is especially pressing, given that the enclosing class for local methods defined in a used to be the (serializable) anonymous function class, but as of Scala 2.12 will be the enclosing class of the lambda. This change is similar in spirit to SI-9408 / 93bee55e. --- test/files/run/t9390b.scala | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 test/files/run/t9390b.scala (limited to 'test/files/run/t9390b.scala') diff --git a/test/files/run/t9390b.scala b/test/files/run/t9390b.scala new file mode 100644 index 0000000000..439e21e0a0 --- /dev/null +++ b/test/files/run/t9390b.scala @@ -0,0 +1,31 @@ +class C { // C is not serializable + def foo = (x: Int) => (y: Int) => x + y + def bar = (x: Int) => (y: Int) => {toString; x + y} +} + +object Test { + def main(args: Array[String]): Unit = { + val c = new C + val f = c.foo + assert(f(1)(2) == 3) + val f1 = serializeDeserialize(f) + assert(f1(1)(2) == 3) + + try { + serializeDeserialize(c.bar) + assert(false) + } catch { + case _: java.io.NotSerializableException => + // expected, lambda transitively refers to this + } + } + + def serializeDeserialize[T <: AnyRef](obj: T): T = { + import java.io._ + val buffer = new ByteArrayOutputStream + val out = new ObjectOutputStream(buffer) + out.writeObject(obj) + val in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray)) + in.readObject.asInstanceOf[T] + } +} -- cgit v1.2.3