当前位置:网站首页>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
🤩
️
边栏推荐
- 一文理解OpenStack网络
- Evolution of the message module of the play live series (3)
- [data mining] final review (sample questions + a few knowledge points)
- kotlin 语言特性
- [one picture series] one picture to understand Tencent Qianfan ipaas
- Troubleshooting the kubernetes problem: deleting the rancher's namespace by mistake causes the node to be emptied
- 【AI玩家养成记】用AI识别邻居家旺财是什么品种
- Gateway processing flow of zuul source code analysis
- CVPR 2022 | interprétation de certains documents de l'équipe technique de meituan
- Brief introduction to cluster analysis
猜你喜欢

Understanding openstack network

‘高并发&高性能&高可用服务程序’编写及运维指南

Getting started with the lvgl Library - colors and images

Opengauss kernel: simple query execution

Internet of things? Come and see Arduino on the cloud

Getting started with the go Cobra command line tool

这几个默认路由、静态路由的配置部署都不会,还算什么网工!

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

敏捷之道 | 敏捷开发真的过时了么?

CVPR 2022 | 美團技術團隊精選論文解讀
随机推荐
YOLOv6:又快又准的目标检测框架开源啦
Sphere, openai and ai21 jointly publish the best practice guidelines for deployment models
How long will it take to open a mobile account? Is online account opening safe?
Kubernetes集群部署
Vipshop's "special sale" business is no longer easy to do?
#yyds干货盘点# 解决剑指offer:调整数组顺序使奇数位于偶数前面(二)
How to create a new empty branch in the web development process of easyrtc?
AGCO AI frontier promotion (6.24)
源碼解析 Handler 面試寶典
Appium installation
Gateway processing flow of zuul source code analysis
CVPR 2022 - Interpretation of selected papers of meituan technical team
发扬连续作战优良作风 全力以赴确保北江大堤安全
TCP triple handshake
Explain the difference between iaas/paas/saas by cooking rice
谁是鱼谁是饵?红队视角下蜜罐识别方式汇总
How stupid of me to hire a bunch of programmers who can only "Google"!
使用 Abp.Zero 搭建第三方登录模块(一):原理篇
How to efficiently analyze online log
I have fundamentally solved the problem of wechat occupying mobile memory