当前位置:网站首页>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
🤩
️
边栏推荐
- How can the new webmaster avoid the ups and downs caused by SEO optimization?
- On the difference between process and thread
- 3. Caller 服务调用 - dapr
- ERR AUTH< password> called without anypassword configured for the default user. Ar
- Richard Sutton, the father of reinforcement learning, paper: pursuing a general model for intelligent decision makers
- Introduction to reptile to give up 01: Hello, reptile!
- 使用 Abp.Zero 搭建第三方登录模块(一):原理篇
- 青藤入选工信部网安中心“2021年数字技术融合创新应用典型解决方案”
- "I, an idiot, have recruited a bunch of programmers who can only" Google "
- Coinbase will launch the first encryption derivative for individual investors
猜你喜欢

一文讲透研发效能!您关心的问题都在

不用Home Assistant,智汀也开源接入HomeKit、绿米设备?

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

Golden age ticket: Web3.0 Security Manual

Getting started with the go Cobra command line tool

Use terminal to activate CONDA service in pypharm (the ultimate method is definitely OK)

LVGL库入门教程 - 颜色和图像

Brief introduction to cluster analysis

Interviewer: the MySQL database is slow to query. What are the possible reasons besides the index problem?

数据科学家面临的七大挑战及解决方法
随机推荐
8 - Format integers and floating point numbers
Why does the kubernetes environment require that bridge NF call iptables be enabled?
Memory introduction
3. caller service call - dapr
The second phase of freshman engineering education seminar is to enroll in the China 100 school peer program
我从根上解决了微信占用手机内存问题
Teach you how to use airtestide to connect your mobile phone wirelessly!
CVPR 2022 | 美团技术团队精选论文解读
1. Snake game design
[one picture series] one picture to understand Tencent Qianfan apaas
"I, an idiot, have recruited a bunch of programmers who can only" Google "
Opengauss kernel: simple query execution
SYSTEMd common component description
Preparation and operation & Maintenance Guide for 'high concurrency & high performance & high availability service program'
System status identifier 'hum' for SAP QM inspection lot
TCP triple handshake
系统测试主要步骤
Comparator 排序函数式接口
AGCO AI frontier promotion (6.24)
Comparator sort functional interface