Kotlin constructors: primary and secondary

前端 未结 2 1399
一生所求
一生所求 2020-12-21 14:07

Just have started with Kotlin, where you can have a primary constructor and secondary ones. The question

2条回答
  •  清歌不尽
    2020-12-21 14:40

    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;
      

提交回复
热议问题