Kotlin constructors: primary and secondary

2019-02-28 03:47发布

问题:

Just have started with Kotlin, where you can have a primary constructor and secondary ones. The question may sound simple, but I couldn't find an answer to it (I've read the "constructors" section in the documentation ) - why?

Basically, I'm trying to understand what is the idea behind being primary and secondary. And what is the difference in how they are used (seems like there's not, so why the separation)?

回答1:

The are various syntactic differences, clearly. But a major conceptual difference is that all secondary constructors ultimately delegate to the primary constructor.

The way I think about this is that the primary constructor is the canonical interface for creating an object, and secondary constructors are like static helpers for transforming other argument sets to comply with this interface.*


* Please note this is a personal interpretation, not backed up with official docs in any way!



回答2:

the kotlin primary constructor help you to write the compact code :

  • you can write class without body, e.g:data class, for example:

    data class Data(val value:String)
    
  • if you don't have any annotation on constructor, then the keyword constructor can be ommitted. a negative example:

    class Foo @Annotation constructor()
    
  • it make the inherit simply, for example:

    open class Bar(val value: String);
    
    class Primary(value: String, other: String) : Bar(value)
    
    class Secondary : Bar {
        constructor(value: String, other: String) : super(value)
    }
    
  • it can using delegations by keyword by, but secondary constructor can't uses.

    interface Rule {
        fun apply(value: String): Int
    }
    
    
    open class Policy(rule: Rule) : Rule by rule;