Kotlin为什么有次要构造函数和初始化块?

huangapple go评论50阅读模式
英文:

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)
    }
}

huangapple
  • 本文由 发表于 2023年6月15日 03:27:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定