概述
kotlin 类初始化
'init'关键字 ('init' keyword)
The primary constructor does not contain any code, so the initialization code can be placed in the initializer block.
主构造函数不包含任何代码,因此可以将初始化代码放在初始化程序块中。
Initializer block prefixed with init keyword.
初始化程序块以init关键字为前缀。
There can be multiple init blocks in a class.
一个类中可以有多个初始化块。
The initializer blocks execute the same order, as they appear in the class body.
初始化程序块执行的顺序与它们在类主体中显示的顺序相同。
Code inside the init blocks executed when class is instantiated.
初始化类时在init块中执行的代码。
All initializer blocks and property initializer is executed before the secondary constructor body.
所有初始化程序块和属性初始化程序都在辅助构造函数主体之前执行。
程序在Kotlin的类中演示Init的示例 (Program demonstrate the example of Init in a Class in Kotlin)
package com.includehelp
// Declaring Class with one Parameter
// in Primary Constructor
class AutoMobile(model:String){
// Declare Property
private var model:String?=null
// Initializer Block
init{
println("First initializer Block ")
// Property initialization in init block
this.model=model
}
// Property initialization in class body
private val modelInUpper=model.toUpperCase()
// Kotlin allow printing properties in the declaration
// itself by using the also function
private val modelLen = "Model Len: ${model.length}".also(::println)
// Second Init Block
init{
println("Second initializer Block ")
println("Model in Upper : $modelInUpper")
}
// Member Function
fun printModel(){
println("Model : $model")
}
}
// Main, Function, Entry Point of Program
fun main(args: Array<String>){
// Create Class Object
val auto = AutoMobile("honda")
// Call Method on AutoMobile Object
auto.printModel()
// Create Class Object
val maruti = AutoMobile("maruti suzuki")
// Call Method on AutoMobile Object
maruti.printModel()
}
Output:
输出:
First initializer Block
Model Len: 5
Second initializer Block
Model in Upper : HONDA
Model : honda
First initializer Block
Model Len: 13
Second initializer Block
Model in Upper : MARUTI SUZUKI
Model : maruti suzuki
翻译自: https://www.includehelp.com/kotlin/example-of-init-in-a-class.aspx
kotlin 类初始化
最后
以上就是壮观季节为你收集整理的kotlin 类初始化_Kotlin程序| 类初始化的例子的全部内容,希望文章能够帮你解决kotlin 类初始化_Kotlin程序| 类初始化的例子所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复