当前位置:网站首页>Kotlin initialization block

Kotlin initialization block

2022-06-24 13:35:00 Hua Weiyun

@[TOC](kotlin Initialization block )


Preface

Use pure code Add The way of annotating , You can understand the source code faster
If you like , Please give me a compliment , In the later stage, we will continue to explain in depth


1、 What is an initialization block init And the Lord 、 The secondary constructor

    User(name = " Zhang San ", age = 21, sex = ' Woman ')      //  The main construction correspondence will be called here      User(name = " Zhang San ", age = 21, sex = ' Woman ', height = 180)      //  This will call the construction correspondence  // user  Property is the primary constructor class User(name: String, age: Int, sex: Char) {    //  This is not Java  Medium  static {}//  Equivalent to Java Of  {}  Building blocks of code //  stay kotlin  in ,  Is an initialization block , init  Building blocks of code     init {        println(" The main constructor is called  $name, $age, $sex")    }    // constructor  Is the main constructor  user  Of   The secondary constructor     constructor(name: String, age: Int, sex: Char, height: Int) : this("tiger", 18, ' male '){        println(" The second constructor was called ")    }}

2、 Construct correspondence initialization sequence

    User(name = " Zhang San ", age = 21, sex = ' Woman ', height = 180)//  First step : Call the main constructor class User(_name: String, age: Int, sex: Char) {//  The second step :  Generate val nName ( In fact, this member variable and  init  It is generated at the same time , It's just  val nName = _name  It's written in init In front of , That's why we execute )    val nName = _name;    init {        val nameValue = nName;    //  The third step :  Generate  nameValue  The details of the         println("init  Code block printing : $nameValue")    }    constructor(name: String, age: Int, sex: Char, height: Int) : this("tiger", 18, ' male '){//  Step four :  Generate the details of the secondary structure         println(" The second constructor was called ")    }}

3、 Delay initialization lateinit

lateinit In use , Lazy loading that requires manual loading

    val lateManager = LateManager()    lateManager.loadRequest()    lateManager.showResponseResult()class LateManager{// lateinit val AAA; val  Is an immutable function , It can't be modified later , It must not be used val    lateinit var responseResultInfo: String      // lateinit  Lazy load mode , In use , Will be loaded //  Simulate server loading     fun loadRequest(){        responseResultInfo = " Server loading succeeded !"    }    fun showResponseResult(){//  because responseResultInfo  Not initialized , A call will directly lead to a crash , Here we use a judgment , Judge  responseResultInfo  Whether to initialize         if (::responseResultInfo.isInitialized){            println("responseResultInfo: $responseResultInfo")        }else{            println(" You haven't initialized yet , Did you forget !")        }    }}

4、 Lazy initialization by lazy

Lazy initialization by lazy When using , self-loading Lazy load mode

    val serverData = ServerData()//  Simulate database loading , Write a timer     Thread.sleep(5000)    println(" Start loading data ")    println(serverData.dataBase)class ServerData{    val dataBase by lazy {        readSqlServerDatabaseAction()    }    private fun readSqlServerDatabaseAction(): String {        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        println(" Data loading , Please wait ......")        return "database data load success ok";    }}

5、 Initialize trap 01

class ServerData{    //  ad locum , it seems , There's no problem with the code , But as we said earlier , Member variables  number  and  init  Is at the same level .//  So it means  init  When it comes to execution , Member variables  number  It's not initialized yet //  Don't put... In here Java Thought , But think in order         init {                number = number.times(9)    // times(9)  finger  number * 9    }    var number = 9}

6、 Initialize trap 02

class ServerData{//  The order of initialization  ServerData -> var info: String -> init -> getInfoMethod() -> info = "tiger"//  This will directly cause info  Back to a null , Because it's entering  init  after , The direct call is getInfoMethod() Method , Now   Member variables  info  Initialization assignment has not been performed yet     var info: String    init {        getInfoMethod()        info = "tiger"    }    private fun getInfoMethod() {        println("info: $info")    }}

7、 Initialize trap 03

//  Write it like this , There seems to be no problem , But combine the code in the function , It's a direct cause of collapse //  When you call   Primary constructor , Pass in info,  Then execute the member variable , call getInfoMethod()  function , When getting the character length , In fact, what you get is null     println(" The character length of the content is :${User("tiger").content.length}")class User(_info: String) {    val content = getInfoMethod()    private val info = _info    private fun getInfoMethod() = info}

summary

🤩
Originality is not easy. , I also hope you guys can support \textcolor{blue}{ Originality is not easy. , I also hope you guys can support }

give the thumbs-up , Your recognition is the driving force of my creation ! \textcolor{green}{ give the thumbs-up , Your recognition is the driving force of my creation !}

Collection , Your favor is the direction of my efforts ! \textcolor{green}{ Collection , Your favor is the direction of my efforts !}

Comment on , Your opinion is the wealth of my progress ! \textcolor{green}{ Comment on , Your opinion is the wealth of my progress !}

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241234579173.html