kotlin 类初始化_Kotlin程序| 类初始化的例子

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 类初始化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值