当前位置:网站首页>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
🤩
️
边栏推荐
- Understanding openstack network
- The 35 "top 100 counties" of tmall 618 agricultural products come from the central and western regions and Northeast China
- 不用Home Assistant,智汀也开源接入HomeKit、绿米设备?
- 黄楚平主持召开定点联系珠海工作视频会议 坚决落实省委部署要求 确保防疫情、稳经济、保安全取得积极成效
- 这几个默认路由、静态路由的配置部署都不会,还算什么网工!
- 源碼解析 Handler 面試寶典
- Appium installation
- 工业物联网(IIoT)的八个主要趋势
- 如何避免严重网络安全事故的发生?
- Why does the kubernetes environment require that bridge NF call iptables be enabled?
猜你喜欢

Getting started with the go Cobra command line tool

黄金年代入场券之《Web3.0安全手册》

Understanding openstack network

One article explains R & D efficiency! Your concerns are

Teach you how to use airtestide to connect your mobile phone wirelessly!

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

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

开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低

Getting started with the go Cobra command line tool

The agile way? Is agile development really out of date?
随机推荐
How can the new webmaster avoid the ups and downs caused by SEO optimization?
The data value reported by DTU cannot be filled into Tencent cloud database through Tencent cloud rule engine
Hands on data analysis unit 3 model building and evaluation
Why did the audio and video based cloud conference usher in a big explosion of development?
金鱼哥RHCA回忆录:DO447管理项目和开展作业--为ansible剧本创建一个项目
Comparator 排序函数式接口
CVPR 2022 | 美团技术团队精选论文解读
如何避免严重网络安全事故的发生?
天猫618农产品“百强县” 35个县域来自中西部及东北
TCP triple handshake
Opengauss kernel: simple query execution
CVPR 2022 - Interpretation of selected papers of meituan technical team
Developer survey: rust/postgresql is the most popular, and PHP salary is low
About the hacked database
Liux command
我真傻,招了一堆只会“谷歌”的程序员!
Party, Google's autoregressive Wensheng graph model
How does webrtc obtain video stream data on the C ++ side?
Nifi from introduction to practice (nanny level tutorial) - environment
Megacli online management raid installation and use steps