Kotlin构造函数(主要构造函数) [英] Kotlin constructor (primary constructor)

查看:116
本文介绍了Kotlin构造函数(主要构造函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Kotlin构造函数有疑问.

I have a question about Kotlin constructor.

class abc {
    constructor(a: Int)
    constructor(a: Int, e: Int)
}

class def(a: Int) {
    constructor(a: Int, e: Int) : this(a)
}

为什么需要在def类中调用此(a)?

Why do I need to call this(a) in def class?

abc类和def类有什么区别?

What is different between class abc and def??

推荐答案

第一个类没有主构造函数,而第二个类具有主构造函数.根据二级构造函数文档,然后必须委派给它.

The first class doesn't have a primary constructor while the second class has one. Per the documentation for Secondary Constructors you then have to delegate to it.

如果类具有主要构造函数,则每个次要构造函数都需要直接或间接通过另一个次要构造函数委派给主要构造函数.使用this关键字将其委派给同一类的另一个构造函数:

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this keyword:

这篇关于Kotlin构造函数(主要构造函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆