Kotlin类的初始化语义是什么? [英] What are the Kotlin class initialisation semantics?

查看:106
本文介绍了Kotlin类的初始化语义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在语言定义中找不到任何能够解释Kotlin中的类初始化的信息.

I haven't been able to find anything in the language definition that explains the initialisation of a class in Kotlin.

import java.util.Properties

fun main(args: Array<String>) {
    val out = MyClass()
    out.fn()
}

class MyClass {
    private val a = Properties() // 1

    init {
        fn()
    }

    public fun fn() {
        println("Fn called.  a = $a")
    }

    //  private val a = Properties() // 2
}

该程序的运行结果会根据属性是在(1)还是在(2)初始化而改变.

The results of running this program change depending whether the property is initialised at (1) or at (2).

我很惊讶声明顺序与该语言相关,并且想了解其背后的决定.我的期望是在调用构造函数体之前先初始化属性.

I'm surprised that the declaration order is relevant in the language and would like to understand the decisions behind this. My expectation would be that properties are initialised before the constructor body is invoked.

推荐答案

我希望属性在构造函数体被调用之前被初始化.

My expectation would be that properties are initialised before the constructor body is invoked.

好吧,init块不是构造函数.这是一种不同的构造,允许您执行对象的初始化,并且它们的[init块]是使用属性初始化程序按声明顺序执行的.

Well, init block is not a constructor. It is a different construct which allows you to perform the initialization of the object and they [init blocks] are performed in the declaration order with the property initializers.

构造函数是不同的野兽,它们在初始化所有属性并执行所有init块之后执行.看下面的例子:

Constructors are a different beast ant they are performed after all the properties were initialized and all init blocks were performed. Look at the following example:

class A(val value: Int) {
    constructor(): this(0) {        
        println("Constructor")
    }    

    init {
        println("Init block")
    }
}

fun main(args: Array<String>) {
    val a = A()
}

输出为:

Init block  
Constructor

您可以将init块放置在任意位置:constructor之前或之后;始终会在A的构造函数(在此示例中为次要构造函数)的之前中执行.

You can place the init block wherever you want: before the constructor or after it; it will always be performed before the A's constructor (secondary constructor, in this example).

这篇关于Kotlin类的初始化语义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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