I think I’d like to be able to do something like the following (clearly garbage) code illustrates:
// Clearly nonsensical
case class Example(a: String) {
def a: Array[Byte] = a.getBytes
}
The gist of it is that I want to write an accessor method for a case class that is named identically to one of its constructor arguments.
I’m using a JSON serialization library called Jerkson that, according to my understanding, will behave in the way I want it to if I define a class in this manner. I’m basing that assumption on this code. Currently, I’m stumped.
If this isn’t possible, could anyone offer some insight on what the Jerkson library code is attempting to do?
Scala automatically creates a method with the same name as any
valdeclared in a class (including the fields of case classes) to support a concept called referential transparency. This is also why you can override adefwith aval. If you’re still skeptical, you can test it yourself like this:First, create a Scala file with a single case class.
Now, compile the file with
scalac. This should result in two classes. For the example above I get MyCase.class (representing the actual case class type) and MyCase$.class (representing the auto-generated companion object for the case class).Now you can examine the resulting
.classfile corresponding to the case class you declared usingjavap. (javapstandard tool for examining Java bytecode—it’s distributed along withjavacin the JDK.)Notice how the resulting class has both a
private final int myField1and apublic int myField1()corresponding to the case class’smyField1field. The same formyField2.On the JVM method return types are not part of the method signature. This means that if two methods have the same name and the same argument types then they’re considered to be conflicting method declarations. This means you can’t declare the
def a: Array[Byte]in your example becauseval a: Stringalready exists, also taking no arguments.Update:
I just looked at the library code and according to the examples the case classes should just work. There is a note in the README saying that parsing case classes does not work in the REPL. Could that be your problem? If not, you should really post the error you’re getting. Edit: Never mind, I see the error you’re talking about in your link to your other post. If I think of a response to that problem I’ll post it over there.