当前位置:网站首页>Basic usage of kotlin

Basic usage of kotlin

2022-07-27 15:12:00 James-Tom

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 .
 Insert picture description here
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 :
 Insert picture description here

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 .

 Insert picture description here
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 .

原网站

版权声明
本文为[James-Tom]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207271411599787.html