Skip to content

Instantly share code, notes, and snippets.

@john-kurkowski
Created August 15, 2011 17:41
Show Gist options
  • Save john-kurkowski/1147286 to your computer and use it in GitHub Desktop.
Save john-kurkowski/1147286 to your computer and use it in GitHub Desktop.
Scala closures capture outer variables, which can lead to unhappy serialization when you don't expect a lazy data structure under the covers. The lesson is, for serialization, favor strict, concrete types.
class A
class B extends Serializable
val baos = new java.io.ByteArrayOutputStream(1024)
val oos = new java.io.ObjectOutputStream(baos)
val streamSurprise: Seq[A] = Stream.fill(3)(new A) // say you don't know it's a Stream under the covers
val transformation = streamSurprise map (a => new B)
oos.writeObject(transformation) // fails due to NotSerializableException: A
oos.writeObject(transformation.toList) // succeeds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment