Monday, May 18, 2020

Kotlin vs java continued

It might be surprising that Kotlin objects are created twice in some cases. This is not really true. Kotlin class have primary and secondary constructors and it is the responsibility of the Kotlin developers to chain them where appropriate. The Language itself matches the constructor by the signature or the tag associated with the constructor during instantiation.
For example,
with the following classes described as 
Class TaskConfiguration @JsonCreator
constructor() {
     var groups = mutableListOf<GroupConfiguration>()
     var counter: CounterConfiguration ? = null
     :
}
Class GroupConfiguration @JsonCreator
constructor() {
     Var numMembers: Int = 0
}
And class
class CounterConfiguration {
    Val numCounters:Int = 0  
     @JsonCreator
     Constructor(@JsonProperty(“numCounters”) numCounters: Int = 100) {
           this.numCounters = numCounters
     }
}
will initialize the ‘groups’ mutableList with two members instead of 1 because the order of progression in the primary constructor is groups first before counter.
On the other hand, if the order is reversed with say:
     var counter: CounterConfiguration ? = null
     var groups = mutableListOf<GroupConfiguration>()
Then, the ‘groups’ is initialized with only one member. 
The CounterConfiguration can be declared differently with a primary constructor to avoid this duplication.
Also the secondary constructor can chain the primary constructor or other constructors with 
Constructor(Parameter parameter1) : this (Parameter parameter2) 
Where the parameters are different.

No comments:

Post a Comment