当前位置:网站首页>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
🤩
️
边栏推荐
- Vim 常用快捷键
- 一文理解OpenStack网络
- How long will it take to open a mobile account? Is online account opening safe?
- 天猫618农产品“百强县” 35个县域来自中西部及东北
- 开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
- Integrated API interface code of domestic express companies for intra city distribution and ordering - Express 100
- MySQL interview questions
- Beauty of script │ VBS introduction interactive practice
- Evolution of the message module of the play live series (3)
- [one picture series] one picture to understand Tencent Qianfan ipaas
猜你喜欢

One article explains R & D efficiency! Your concerns are

硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件

Getting started with the lvgl Library - colors and images

Who is the fish and who is the bait? Summary of honeypot recognition methods from the perspective of red team

我从根上解决了微信占用手机内存问题

How stupid of me to hire a bunch of programmers who can only "Google"!

CVPR 2022 | 美團技術團隊精選論文解讀

Quickly understand the commonly used message summarization algorithms, and no longer have to worry about the thorough inquiry of the interviewer

华为 PC 逆势增长,产品力决定一切

Definition and use of constants in C language
随机推荐
kotlin 关键字 扩展函数
Getting started with the go Cobra command line tool
青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
8 lines of code to teach you how to build an intelligent robot platform
1. Snake game design
Creation and use of unified links in Huawei applinking
黄金年代入场券之《Web3.0安全手册》
ERR AUTH< password> called without anypassword configured for the default user. Ar
System status identifier 'hum' for SAP QM inspection lot
【AI玩家养成记】用AI识别邻居家旺财是什么品种
Cohere、OpenAI、AI21联合发布部署模型的最佳实践准则
硬件开发笔记(六): 硬件开发基本流程,制作一个USB转RS232的模块(五):创建USB封装库并关联原理图元器件
How can the new webmaster avoid the ups and downs caused by SEO optimization?
"Interesting" is the competitiveness of the new era
What should I do if I fail to apply for the mime database? The experience from failure to success is shared with you ~
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
实现领域驱动设计 - 使用ABP框架 - 创建实体
数据科学家面临的七大挑战及解决方法
金鱼哥RHCA回忆录:DO447管理清单和凭据--为访问清单主机创建机器凭据
kotlin 协程 lanch 详解