当前位置:网站首页>Basic usage of kotlin
Basic usage of kotlin
2022-07-27 15:12:00 【James-Tom】
Catalog
1、 summary
“ If you are for Android Develop and find an alternative programming language , Then we should try Kotlin. It's easy to be in Android Substitute... In the project Java Or the same Java Use it together .”–Hathibelagal
Kotlin v1.0 On 2016 year 2 month 15 Promulgated by the . This is considered the first official stable version , also JetBrains Ready for long-term backward compatibility starting with this release .
stay Google I/O 2017 in ,Google Announce on Android Up for Kotlin Provide the best support .
Time passed quickly ,Kotlin Language has been released 3 Years. , As Android For developers ,kotlin Language will become a new language that we have to master , Especially kotlin Language introduction process (Coroutine) After this feature , More obvious advantages .
Kotlin+Mvvm Such a composite architecture has gradually become the mainstream , Bloggers are using this architecture for project development , The amount of code is greatly reduced , The frame structure is clear , I recommend you to learn and master , Later, I will write the architecture used in the project independently , Welcome to Follow this blog follow-up .
2、 How to create a class
for instance :
ResLogin.kt
class ResLogin {
var code = -1
var msg = ""
var token = ""
lateinit var retObj: RetObjBean
inner class RetObjBean {
var id = 0
var name = ""
}
}
Corresponding Json character string :
{
"retCode": 0,
"retMsg" : "success",
"retObj ": {
"id":378,
"name":"admin"
},
"token" : "3b6abdb79b29d6ce33b71c9da5d30de6"
}
After the attribute declaration, it will be automatically generated get,set Method , We use it directly through ( Class . Property name ) Perform assignment and value taking operations .
for example :
var login = ResLogin()
login.code = 0 // assignment amount to set Method
print(login.retMsg) // Value amount to get Method
And java There are differences in classes 4 It's about :
(1)、var:
Declare keywords for attribute variables , The data type of the attribute can be automatically inferred from the assignment
(2)、lateinit :
This keyword yes late init A combination of two words , That is, delay initialization , You don't need to copy it as null, Instead, wait until you need it to be used .
Be careful :lateinit Modification cannot modify the original data type (byte,char,short ,int,long,float,double), But it can be decorated String, And custom class Class etc. .
When we don't add this keyword, we will report the following error .
lateinit Refer to
(3)、 inner class:
And java Of static class Declare that the usage of static inner classes is the same , Just different keywords , because kotlin No more static Keyword. .
(4)、lateinit var retObj: RetObjBean:
Declare a as RetObjBean Type of retObj attribute . This is a strange way of writing , The type of property is : Post written , And java Completely different , So you need to get used to .
3、 Subclass inherits parent
for instance :
ProjectApplication .kt
class ProjectApplication : Application() {
override fun onCreate() {
super.onCreate()
LitePal.initialize(this)
context = this
}
companion object {
lateinit var context: Context
}
}
And java There are differences in the way inheritance is written 2 It's about :
(1)、 :Application()
Use :+ Parent class name () This way to inherit the parent class , Different from our original writing ,: It stands for inheritance ,Application Represents the name of the parent class , () Represents the default constructor of the parent class .
(2)、override fun onCreate()
The method of overriding the parent class also changes ,override Rewrite keywords for ,fun Represents the keyword that declares a method and class The key is the same , Similar action ,onCreate Method name ,() Is a formal parameter .
Let's focus on this code :
companion object {
lateinit var context: Context
}
companion object : translate become The meaning of the accompanying object , Belongs to the class itself , therefore companion object It can't be defined in the global without class .
It is similar to Java Inside static Variable , Direct class name dotting call .
Such as :
4、 Declare a function with a return value
for instance :
/** * Date formatting * * @param date Date to format * @param pattern Time format , Such as :yyyy-MM-dd HH:mm:ss * @return Return the formatted time string */
fun format(date: Date, pattern: String): String {
val sdf = SimpleDateFormat(pattern)
return sdf.format(date)
}
You can see that the formal parameter declaration is the same as the attribute declaration : Parameter type after colon .
Notice the return value information of the function , Directly follow the parentheses of the function with (: return type ) The way .
Calls and java It's the same .
5、for How to write a cycle
and java There is a little difference in the way of writing , Turned into in and … keyword .
for instance :
for (index in 0..3) {
print(index.toString())
}
Output results :
0
1
2
3
6、 summary
The content of this article is relatively simple ,kotlin A shortcut to language learning , Just use it 、 Use it 、 Or use it . Only skilled use , Corresponding to the back MVVM The combination of architecture will be of great benefit .

WeChat official account : A dusty journey
There are a lot of things I want to say to you , It's like chatting with friends .
Write code , To do a design , Talking about life , Talk about work , Talk about the workplace .
What is the world I see ?
Search and follow me .
The content of official account is different from that of blog .
边栏推荐
- Principle of MOS tube to prevent reverse connection of power supply
- 如何帮助企业优化Office管理
- STM32 CAN 通信 滤波设置问题
- 【WORK】关于技术架构
- Notice on printing and distributing the Interim Measures for the administration of green manufacturing pilot demonstration of Shenzhen Bureau of industry and information technology
- LeetCode 456. 132模式 单调栈/medium
- USB接口电磁兼容(EMC)解决方案
- STM32 can communication filter setting problem
- Tencent two sides: @bean and @component are used in the same class, what will happen?
- How to do well in enterprise system vulnerability assessment
猜你喜欢
![[work] about technical architecture](/img/24/f3402c04157ce9a8846580f017f472.png)
[work] about technical architecture

Visual system design example (Halcon WinForm) -9. text display

TL431-2.5v基准电压芯片几种基本用法

If we were the developer responsible for repairing the collapse of station B that night
MOS管防止电源反接的原理

如何做好企业系统漏洞评估

What is tor? What is the use of tor browser update?

Kotlin的基础用法

被动收入:回归原始且安全的两种赚取方法

仅做两项修改,苹果就让StyleGANv2获得了3D生成能力
随机推荐
Visual system design example (Halcon WinForm) -9. text display
STM32F10x_硬件I2C读写EEPROM(标准外设库版本)
NEFU118 n! How many zeros are there after [basic theorem of arithmetic]
Notice of Nanshan District Civil Affairs Bureau on carrying out the grade evaluation of social organizations in Nanshan District in 2022
TL431-2.5v基准电压芯片几种基本用法
Nefu117 number of prime numbers [prime number theorem]
Unityui aspect processing (induction and accumulation)
Notice of Shenzhen Municipal Bureau of human resources and social security on the issuance of employment related subsidies for people out of poverty
The database uses PSQL and JDBC to connect remotely and disconnect automatically from time to time
网络设备硬核技术内幕 路由器篇 4 贾宝玉梦游太虚幻境(下)
Visual system design example (Halcon WinForm) -10. PLC communication
adb命令 (安装apk包格式:adb install 电脑上apk地址包名)
Nefu119 combinatorial prime [basic theorem of arithmetic]
How to do well in enterprise system vulnerability assessment
反射
LeetCode 190. 颠倒二进制位 位运算/easy
Lesson 3: SPFA seeking the shortest path
LeetCode 341.扁平化嵌套列表迭代器 dfs,栈/ Medium
工具 - markdown编辑器常用方法
JMeter recording interface automation