为什么Kotlin有两种类型的构造函数

为什么Kotlin有两种类型的构造函数

本文介绍了为什么Kotlin有两种类型的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin具有两种类型的构造函数,即主要构造函数和次要构造函数.拥有两种类型的目的是什么?我认为,这会使代码更加复杂和不一致.如果两种类型的构造函数都创建类的对象,则它们对类同样重要.

Kotlin has two types of constructors, primary and secondary. What is the purpose of having two types? In my opinion it makes the code more complicated and inconsistent. If both types of constructors create objects of a class, they are equally important to a class.

同时,多个初始化程序也会引起混乱并降低可读性.

Meanwhile, multiple initialisers also introduce confusion and reduce readability.

推荐答案

当您需要将作为构造函数参数传递的值保存到实例的属性时,主要构造函数涵盖了流行的用例.

Primary constructors cover the poplular use case when you need to save the values passed as the constructor arguments to the properties of the instance.

基本上,主构造函数为声明属性和从构造函数参数初始化属性提供了一种快捷方式.

Basically, a primary constructor provides a shorthand for both declaring a property and initializing it from the constructor parameter.

请注意,您完全可以不使用主构造函数而完成相同的操作:

Note that you can do the same without primary constructors at all:

class Foo {
    val bar: Bar

    constructor(barValue: Bar) {
        bar = barValue
    }
}

但是,由于这种情况确实经常发生在代码库中,因此Kotlin主要构造函数的作用是在此处减少样板:

But, since this happens really often in the codebases, Kotlin primary constructors serve the purpose of reducing the boilerplate here:

class Foo(val bar: Bar)

次要的构造函数可以补充或替换主要的构造函数,以支持单个类的多个构造例程.

Secondary constructors may complement or replace the primary one in order to support several construction routines for a single class.

这篇关于为什么Kotlin有两种类型的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:12