在kotlin类中创建辅助构造函数的正确位置是什么?

问题描述 投票:0回答:1

在init块上方或下方创建二级构造函数的正确位置是什么?

class Bottle(bottleShape: String, capacity: Int, color: String): Container( bottleShape, capacity) {

private var closed: Boolean = true
    val bottleColor: String

 constructor(bottleShape: String, capacity: Int): this (bottleShape, capacity, "Transparent")

    init{

        closeAble = true
        bottleColor = color
        println(bottleColor)

    }
}
kotlin
1个回答
0
投票

显然,这只是一个约定,但是在the official documentation on class layout之后,要求顺序:

  • 属性声明和初始化程序块
  • 二级构造函数
  • 方法声明
  • 伴侣对象

我将初始化放在辅助构造函数之前。

© www.soinside.com 2019 - 2024. All rights reserved.