英文:
Why does Kotlin has secondary constructor and init block?
问题
Kotlin有主要构造函数、次要构造函数和init块。我们不能在主要构造函数中执行任何代码。因此,Kotlin提供了一个init块,在实例创建后立即执行其中的代码。
我找不到任何问题,不能通过主要构造函数和init块解决。我认为这与性能问题无关。
我的问题是为什么我们需要次要构造函数,以及为什么我们应该使用次要构造函数?
英文:
Kotlin has primary and secondary constructors and init block. We can not execute any code in the primary constructor. Because of this Kotlin provides an init block which executes the code inside just after the instance is created.
I couldn't find any problem that can't solve with primary and init block.
I don't think it's about any performance issue.
My question is why do we have a secondary constructor and why we should use a secondary constructor?
答案1
得分: 4
只返回翻译好的部分:
这是用于可能需要向构造函数传递不同参数类型的情况。
例如,假设您有一个表示人和他们的出生月份的类。出生月份用Month枚举类表示。但有时将月份的数字表示作为Int使用可能更方便。
或者,如果您正在构建一棵树,那么在创建节点时自动将节点添加到其父节点可能会很方便。
英文:
It's for cases where you might want to pass different parameter types to the constructor.
For example, suppose you have a class representing a person and their birth month. The birth month is represented with the Month enum class. But it might be convenient to sometimes use the numerical representation of the month as an Int.
data class Person(
val name: String,
val birthMonth: Month
) {
constructor(name: String, birthMonth: Int): this(name, Month.of(birthMonth))
}
Or if you're building a tree, it might be convenient to be able to have the option to automatically add the node to its parent when creating it:
class Node(
val name: String
) {
val children = mutableListOf<Node>()
constructor(name: String, parentNode: Node): this(name) {
parentNode.children.add(this)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论