0

Say I have a case class Declared like this:

case object DoubleType {
  type JvmType = Double
}
case class DoubleLiteral(value: Double) {
  type fieldType = DoubleType.JvmType
  val dt = DoubleType
  val typeWidth = 8
  //methods here after
}

What's scala's behaviour on serializing DoubleLiteral(2.0)? Does it just serialize value? Or it will also serialize fieldType, dt and typeWidth? If so, should I annotate fieldType, dt and typeWidth as @transient?

yjshen
  • 6,583
  • 3
  • 31
  • 40

1 Answers1

0

Type members like fieldType only exist at compile-time, they have no influence on the run-time structure of an object or its serialization. This is because of the JVM's type erasure, and applies to both type members and type parameters.

Fields like dt and typewidth are just as much a part of an instance of a case class as fields declared in the constructor like value. They will all be serialized. You can prevent serialization with @transient, but for static values like dt and typewidth it may be better to prevent them from becoming fields in the object at all. The easiest way to do this is to declare each field as a def. All access is done through accessor methods in Scala anyway, so there is no performance cost from this.

wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
  • Could you show the assertion about private final? `scala> class Foo { private final val foo: Int = 5 ; def x = foo }` and `scala> :javap -prv Foo`? Sorry I'm too lazy ATM to try all combos of keywords. – som-snytt Jul 18 '14 at 05:53
  • @som-snytt That assertion was wrong, I was misremembering. I've edited in something better, but take a look here: http://stackoverflow.com/questions/13412386/why-are-private-val-and-private-final-val-different – wingedsubmariner Jul 20 '14 at 03:24
  • Not to nit-pick impl details, but this emits a field: `class X { private final val x = 8 ; def y = x }`. The field is unused. – som-snytt Jul 21 '14 at 11:01
  • You're right, `javap` clearly shows a field, despite `scalac -Xprint` saying it won't create one. Maybe it's a Java interop thing? – wingedsubmariner Jul 23 '14 at 13:23
  • That's interesting. What -Xprint do you mean? I would say interop if the field were initialized. – som-snytt Jul 24 '14 at 03:49
  • `-Xprint:constructors` is the last one that prints a tree, and it has a `def x` but no `val` for `x`. `javap` shows that the field is never initialized. It makes no sense. – wingedsubmariner Jul 24 '14 at 04:09