0

In a Scala case class, I have a Boolean function definition whose name starts with "is" - the function name is "isCreated". I realized that once I serialize object instances of this class into Json using fasterxml/Jackson, a redundant field with the name 'created' is added to the representation. However, if I change the function name to something else that does not start with "is" (s.a. simply "created"), object instances are created just fine with no redundant field. Is there any special meaning associated with function definitions whose names start with "is" in Scala that triggers code-gen to add a field to objects of that type ?


case class Account(
    name: String,
    balance: Double,
    status: AccStatus) {

  // [.. some code ..]

  def isCreated: Boolean = (status.tag == true)
}
Pouria
  • 155
  • 3
  • 12
  • 1
    Which library are you using to serialize the case class? – Luis Miguel Mejía Suárez Aug 30 '19 at 17:31
  • I am using fasterxml/Jackson for serialization. – Pouria Aug 30 '19 at 17:40
  • 2
    I would suggest using a **Scala** specific JSON library _(like [`circe`](https://circe.github.io/circe/))_. **Jackson** was intended for **Java** and uses _reflection_ to generate the JSONs. Apparently, the [that is the intended behavior](https://stackoverflow.com/questions/32270422/jackson-renames-primitive-boolean-field-by-removing-is) of the library. At runtime the **Scala** code was transformed to a very different byte code, probably that def was inlined to a field. – Luis Miguel Mejía Suárez Aug 30 '19 at 17:50

1 Answers1

0

The company where I work used Jackson before we switched to Circe, and I have seen the feature you described. I believe it is because Jackson assumes "isCreated" is a getter for the "created" private variable of type Boolean, and creates a field for it in the JSON. Recall that Jackson was originally written for Java. In Scala, we do not have getters and setters, so this feature is not helpful for us.

Allen Han
  • 1,163
  • 7
  • 16
  • 3
    Scala has getters and setters, but they are of the form `x()` and `x_=(y)`. – som-snytt Aug 30 '19 at 18:03
  • 1
    I found a link that elaborates on som-snytt's correction. Look here for more details: https://www.dustinmartin.net/getters-and-setters-in-scala/ – Allen Han Aug 30 '19 at 19:45