DEV Community

Discussion on: Kotlin - The Good, the Bad and the Ugly

Collapse
 
cjbrooks12 profile image
Casey Brooks

About primary constructors, you definitely don't have to list all the properties in the class. Just the ones you want initialized in a constructor. I will agree that the syntax is a bit quirky, but overall I've found them to be quite helpful. I had adopted a pattern in java of always chaining overloaded constructors to a single, "root" constructor, passing the default values along the way, to ensure all objects are initialized the same way. Kotlin just enforces this pattern.

I also prefer a different syntax for declaring primary constructors, which makes it easier to read.

@ClassAnnotation
class ClassName
@PrimaryConstructorAnnotation
constructor(
        val1: String,
        val val2: Int,
        private val val3: Double
) : SuperClass(val1) {
...
}

This format makes it very clear which annotations go where (and I use @Inject on nearly all of my classes, so is quite necessary for me to have the constructor keyword even in the primary one), and also keeps properties each on their own lines, just like when declared in the class body.

Collapse
 
martinhaeusler profile image
Martin Häusler

Thanks for sharing your experience. This way of formatting improves the situation a little. However, for me it's still counter-intuitive. When I open up the source code of a class file, there are three things that I am primarily interested in:

  1. what kind of class is it? (regular class, interface, enum...)
  2. what's the name of the class?
  3. what is the base class, and what are the interfaces?

While the "Kotlin way" satisfies 1 and 2, it fails on 3. Look where the base class is located. Somewhere way down there. The very concept of declaring fields (which belong to the class) within a constructor is appalling to me. A constructor is a member of a class. Why should it contribute to the structure of the class (in terms of fields in this case)? I realize that this is not really the case, but the syntax makes it look as if that was happening. Maybe it's just because I've written so much Java and C#.