To answer your first question: yes you can treat it as a Java Serializable object:
scala> @serializable object A
defined module A
scala> import java.io.ByteArrayOutputStream;
import java.io.ByteArrayOutputStream
scala> import java.io.ObjectOutputStream;
import java.io.ObjectOutputStream
scala> val baos = new ByteArrayOutputStream(1024)
baos: java.io.ByteArrayOutputStream =
scala> val o = new ObjectOutputStream(baos)
o: java.io.ObjectOutputStream = java.io.ObjectOutputStream@3d689405
scala> o.writeObject(A)
scala> baos.toByteArray
res4: Array[Byte] = Array(-84, -19, 0, 5, 115, 114, 0, 24, 108, 105, 110, 101, 49, 51, 36, 111, 98, 106, 101, 99, 116, 36, 36, 105, 119, 36, 36, 105, 119, 36, 65, 36, 110, -104, -28, -53, -123, -97, -118, -36, 2, 0, 0, 120, 112)
scala> object B
defined module B
scala> o.writeObject(B)
java.io.NotSerializableException: B$
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
at .(:13)
at .()
at RequestResult$.(:9)
at RequestResult$.()
at RequestResult$scala_repl_result()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$18.apply(Interpreter.scala:981)
at scala.tools.nsc.Interpreter$Request$...
If you want to serialize to some string format, perhaps this library may be useful, which serializes scala objects into JSON.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…