Learning from beginning to end of Android cultivation manual Kotlin [complete]

Sharing of previous articles

Click jump = > stay up late and fight Android again from bronze to King - development efficiency plug-in
Click jump = > unity particle special effects series - Tornado preform is ready, and the unitypackage package can be used directly!
Click jump = > my sister asked me to unlock the new skills of dolls: FairyGUI, realize List nesting List / Three-dimensional Gallery in Unity, and play with flowers
Click jump = > unity novice must have 5 treasure plug-ins - the latest version of white whoring worth thousands of yuan

This article has 13000 words and takes 30 minutes to read

👉 About the author

As we all know, life is a long process, constantly overcoming difficulties and constantly reflecting on the process of progress. In this process, there will be a lot of questions and thoughts about life, so I decided to share all my thoughts, experiences and stories in order to find resonance!!!
Focus on Android/Unity and various game development skills, as well as various resource sharing (website, tools, materials, source code, games, etc.)
If there is any need to welcome private self, exchange group, so that learning is no longer lonely.

👉 premise

Current environment

The latest download of patch 2 version 2020.3.1 on October 8, 2021

👉 Practice process

😜 variable and constant

Variable variable definition: var keyword

Var < variable name >: < type > = < initialization value >

Immutable variable definition: val keyword, a variable that can only be assigned once (similar to the variable modified by final in Java)

Val < variable name >: < type > = < initialization value >

Variables can be determined automatically without specifying the type. There can also be no initial value, but it must be initialized before use

val TempOne = "This is an immutable variable"
var TempTwo = "This is a variable"
var TempThree = "Official account: Mr. null name"
val TempFour: String = ""

In short, you can have an initialization value before declaration. (can we avoid null pointers by forcing the initial value to be written?)

Once a variable has an assignment, she infers the type by herself, and cannot change later. For example, if the initial value of a variable is a number, the subsequent change quantity cannot be assigned as a string, nor can methods in other types be called. There is one type except [Any]

😜 Foundation type

Although the declarations are [var] and [val], Kotlin still has types [Byte], [Short], [Long], [Float], [Double], and [String], [Noolean], as well as [Any]

var numberOne:Int? = 1
var numberTwo:Int? = 1
var numberThree = numberOne
Log.e("TAG", "Sesame seed output 7: They have the same address:" + (numberThree === numberOne))
//According to the normal idea, these two variables are different and should not be equal. The output of the result is equal, which will be left as a question later
Log.e("TAG", "Sesame seed output 7: They have the same address:" + (numberOne === numberTwo))
Log.e("TAG", "Sesame seed output 7: They have the same address:" + (numberThree === numberTwo))
Log.e("TAG", "Sesame seed output 7: They are the same:" + (numberOne == numberTwo))

//2021-10-13 10:30:42.460 31093-31093/cn.appstudy E/TAG: sesame seed output 7: their addresses are the same: true
//2021-10-13 10:30:42.460 31093-31093/cn.appstudy E/TAG: sesame seed output 7: their addresses are different: true
//2021-10-13 10:30:42.460 31093-31093/cn.appstudy E/TAG: sesame seed output 7: their addresses are different: true
//2021-10-13 10:30:42.460 31093-31093/cn.appstudy E/TAG: sesame seed output 7: their contents are equal: true\

Array types are also essential

  var listOne = arrayOf(1, 2, 3)
        var listTwo = intArrayOf(1, 2, 3)
        var listThree = arrayListOf<String>()
        listThree.add("This is")
        listThree.add("array")
        listThree.add("List")

If there is an array, there must be a circular reading. See the circular control section for details

😜 character string

The string supports multiple lines of characters, using three double quotation marks [""], but there are few application scenarios for multiple lines. Xiaokong has developed several products and has not used them.

var strignOne = "Official account:"
var strignTwo = "Mr. empty name"
if (strignOne.equals(strignTwo)) {
    Log.e("TAG", "Sesame seed output 6: They are equal in content")
} else {
    Log.e("TAG", "Sesame seed output 6: Their content varies")
}

😜 Type conversion

This is different from Java in that there are no conversion functions such as [String. valueOf] and [Integer.valueOf], but the form of [to] (click to after the direct variable). For example:

  var Temp="1234"        var TempOne=Temp.toInt()
  • toByte(): Byte, converted to bytes
  • toShort(): Short, converted to short integer
  • toInt(): Int, converted to integer
  • toLong(): Long, converted to long integer
  • toFloat(): Float, converted to floating point
  • toDouble(): Double, converted to double floating point type
  • toChar(): Char, converted to character type

😜 Function definition

The default definition is like this. The [fun] keyword indicates a function definition

private fun methon(height: Int): Int { //The types are: after (pay attention to the colon), and the variables are before
    return height+1;
}

In this way, the function can directly use [=] for assignment operation

private fun methon(height: Int): Int = height + 1;

In addition to the above, it is a little more than Java: the return of functions supports judgment statement operations, as follows

fun  methonTwo(height:Int):String{
    return  if (height>10){
        "More than 10 walk if"
    }else{
        "Otherwise go else"
    }
}

Moreover, the assignment operator just mentioned above can also be combined with the judgment form,

private fun methon(height: Int): String = if (height > 10) {
    "More than 10 walk if"
} else {
    "Otherwise go else"
};

😜 Anonymous function

val stringLengthFunc: (String) -> Int = { input ->
        input.length
}

The above example is an anonymous function, which receives a String type parameter and returns the String length int type after being processed by the anonymous function. The call is as follows:

val stringLength: Int = stringLengthFunc("I Love Android")

Note that the input in anonymity is written at will. You can also change it to another name, not a special keyword of the system

😜 Variable parameters

In Java, it is the... Symbol (note three points), and Kotlin is the [vararg] keyword

That is, an uncertain number of parameters can be used in the method definition, and different numbers of parameter calls can be used for the same method.

Interestingly, in Java, there are variable parameters, but the variable parameters are the number, and the types need to be consistent. (if any boss knows that the types can also be variable, welcome to browse and discuss)

Kotlin not only supports number, but also supports different data types.

Ah, I suddenly remembered that if the variable parameter in Java is written as Object type, in fact, multiple types can be passed when calling.

😜 Null check

Null security is Kotlin's propaganda feature, but it is not insensitive. In fact, it depends on the mandatory code specification to make your code have good null judgment. Although Java can also do it, because it is a subjective consciousness, anyone can pull down.

So Kotlin comes to help us do this. If you don't comply with it, you can't compile the project directly.

Therefore, the variable declaration cannot be empty and requires special processing, which is very similar to [TypeScript].

Adding [!!!] (double exclamation mark) after the field will throw an empty exception. Adding [?] means that it can be empty. The default variable cannot be empty and an error will be reported.

//Type followed by "? Indicates that it can be empty
var myAge: String? = "666"
myAge = null
//A null pointer exception is thrown when the variable is null
val ageZero = myAge!!.toInt()
//If myAge is determined to be empty, ageOne is also empty
val ageOne = myAge?.toInt()
Log.e("TAG", "Sesame seed output 1: " + ageOne)
//When myAge is empty, - 1 is returned
val ageTwo = myAge?.toInt() ?: -1
Log.e("TAG", "Sesame seed output 2: " + ageTwo)

😜 Type check

There is the [instanceof] keyword in Java to detect whether it is a certain type, and there is also the [is] keyword in Kotlin

//Type followed by "? Indicates that it can be empty
var myAge: String? = "666"
if (myAge is String) {
    //Judge whether the variable myAge is of string type
}

Kotlin has an [Any] type, which can be automatically converted in combination with [is], as follows:

//Type followed by "? Indicates that it can be empty
var myAge: Any? = "666"
if (myAge is String) {
    //Judge whether the variable myAge is of string type
    Log.e("TAG", "Sesame seed output 0: ${myAge.length}")
}

😜 section

This is a new word. As the name suggests, it is a mathematical interval, such as all numbers from 1 to 10. Use [...] to implement. Note that two points are not three points. Don't confuse them with Java variable parameters.

I haven't thought of the application scenario yet

for (i in 1..6)
  Log.e("TAG", "Sesame seed output 3: $i") // Output "123456"
for (i in 1..6 step 2)
  Log.e("TAG", "Sesame seed output 4: $i")// Set the step size. The step size and interval are different. The interval is that the step size is reduced by one to output "135"
//If there is positive order, there is flashback
for (i in 6 downTo 1)
  Log.e("TAG", "Sesame seed output 5: $i") // Output "654321"

😜 Conditional statement

Almost all programming languages are common, and there is no difference between [if], [else], [else if].

Only a little more is that you can directly assign a value in front of the conditional statement if. Provided that the returned types are consistent.

var TempTwo = 10;
var TempThree = if (TempTwo == 10) {
    "Return equality"
} else {
    "Unequal return"
}
Log.e("TAG", "Sesame seed output 9: $TempThree")

There is no switch usage in Kotlin, but when syntax. Else is similar to the default of switch. Other branches are not satisfied with this else. If multiple processes judge the same, break is removed from Java switch, and when is directly separated by comma.

var TempFour = 8;
when (TempFour) {
    in 1..5 -> {
        Log.e("TAG", "Sesame seed output 10: Can only use in Judge whether it is within an interval")
    }
    2,3,4->{
        Log.e("TAG", "Sesame seed output 10: Variables 2 or 3 or 4 go here")
    }
    5 -> {
        Log.e("TAG", "Sesame seed output 10: She will judge whether it is 5 or 8")
    }
    8 -> {
        Log.e("TAG", "Sesame seed output 10: The variable is 8, so walk")
    }
    else -> {
        Log.e("TAG", "Sesame seed output 10: It doesn't walk up there. It's similar switch of default")
    }
    //The type of judgment shall be consistent with that in when bracket
    //"If character" - > {}
}

Alas, there are still some about the use of when. I don't think it's possible to use it, so I won't mention it, but this is a key point. Digression: the whole is flowery, which is not as easy to understand as Java. Jie is Jie, but it's not simple. You have to think for a while to understand the meaning.

😜 Cycle control

Loop is a kind of control frequently used in code. Although loop is also a for keyword in Kotlin, its self increment and self decrement are very different

var listThree = arrayListOf<String>()
listThree.add("This is")
listThree.add("array")
listThree.add("List")
for (idnex in 1 until 10) {
    //This is a 1-10 loop equivalent to for (int i = 1; I < 10; I + +)
}
for (idnex in 10 downTo 1) {
    //This is a 1-10 loop equivalent to for (int i = 10; I > 0; I --)
}
for (idnex in 1..10) {
    //This is a 1-10 loop equivalent to for (int i = 1; I < = 10; I + +)
}
for (index in 1..10 step 2) {
    //This is a loop that increments by 2 for (int i = 1; I < = 10; I + = 2)
}
for (intss in listThree) {
    Log.e("TAG", "Sesame seed circulation: $intss")
}
for (intss in listThree.indices) { //What you get is the angular position index
    Log.e("TAG", "Sesame seed circulation: " + listThree[intss])
}

while is no different from do... while loops and Java.

Return and jump

Support return break continue in Java. There is no difference in syntax, but there is an additional tag function, that is, break continue can jump to the loop you specify, such as the nesting of a five loop. By default, break continue can only return the current loop, but with tags, they can jump out of the upward loop at will: for example, directly jump out of all loops.

The label is composed of the + @ symbol you can name casually

As follows:

//https://zhima.blog.csdn.net/
one@ for (i in 1..100) {
    Log.e("TAG", "Sesame seed circulation i: $i")
    two@ for (j in 1..100) {
        if (j > 2) {
            Log.e("TAG", "Sesame seed circulation j: $j")
            //When J > 2 is satisfied, break will jump out of these two cycles directly because it is @ one
            break@one
        }
    }
}

Output only these two:
2021-10-13 17:08:29.820 10437-10437/cn.appstudy E/TAG: sesame seed cycle i: 1
2021-10-13 17:08:29.820 10437-10437/cn.appstudy E/TAG: sesame seed cycle j: 3

😜 Classes and objects

Class is also created using the [class] keyword

class Entity {
     var name: String? = null
     var urlJUEJIIN: String? = null
     var urlCSDN: String? = null
     var urlList: List<String>? = null
}

The new keyword is not used during initialization

var tempEntity = Entity() / / equivalent to java's Entity tempEntiy=new Entity();

tempEntity.name = "this is my name" / / click the attribute inside

In Java, there can be multiple constructors, all of which are class names. There are some differences in Kotlin

  1. There is a distinction between primary and secondary constructors
  2. Primary and secondary constructors are recommended to exist separately, because they require special processing to exist at the same time
  3. There is an initialization function. As long as this class is created, the contents of the initialization function must be executed

How to modify the access rights of constructors?

The secondary constructor is written directly in front of the function, and the primary constructor is written before the class name of the function

class Entity {
    init {
        Log.e("TAG,", "Class. The keyword is init-Built in system ")
    }

    var name: String? = null
    var urlJUEJIIN: String? = null
    var urlCSDN: String? = null
    var urlList: List<String>? = null

    constructor() {

    }

    private constructor(name: String) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) {
        Log.e("TAG,", "Constructor executed $name===$age")
    }
}

//These are two classes. Don't confuse them in the two files

//This is the main constructor, which uses the keyword constructor directly after the class name
class Person private constructor(name: String, age: String) {
    init {

    }

    //Special treatment: if the primary structure and secondary structure exist at the same time -- the parameter content of the primary structure must be included
    constructor(name: String, age: String, height: Int) : this(name, age) {

    }
}

//2021-10-14 14:52:59.468 10639-10639/cn.appstudy E/TAG: initialization function of class. The keyword is built-in in init system
//2021-10-14 14:52:59.468 10639-10639/cn.appstudy E/TAG: constructor test performed = = = 20

So what if class inheritance?

If the parent class has a constructor, the child class must also have at least one. If it is insufficient, the editor will prompt a warning

The method of using the parent class also uses the [super] keyword, and the parent class needs the [open] keyword

//https://zhima.blog.csdn.net/
open class Entity {
    init {
        Log.e("TAG,", "Class. The keyword is init-Built in system ")
    }

    constructor() {

    }

    constructor(name: String) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) {
        Log.e("TAG,", "The parent constructor was executed $name===$age")
    }
}

 
class EntityTwo : Entity {
    constructor() {

    }

    constructor(name: String) : this(name, 0) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) : super(name, age) {
        Log.e("TAG,", "Subclass constructor executed $name===$age")
    }
}

😜 Get and Set

In fact, after Kotlin declares the entity class, the variables in it have set and get attribute functions by default. Unless you want special business content.

For example, set needs to perform other business processing in combination with the project, and the same is true for get.

[filed] is a built-in keyword in the system and is regarded as an intermediate variable

Except these

var name: String? = null
        set(value) { //Name yourself at will
            field = value  //This field is built-in in the system and used in get
        }
        get() {
            return field + "This is a return"
        }
var urlJUEJIIN: String? = null
        get() =field+"This is only get"
var urlCSDN: String? = null
var urlList: List<String>? = null

😜 inherit

In Java, it can be said that all classes inherit from Object, while in Kotlin, it can be said that all classes inherit from Any class.

Inherit and use the keyword [extends] in Java, and use [:] (English colon) in Kotlin

In addition, whether it is method rewriting or attribute variable rewriting, the [override] keyword is added in front, which is the same as Java

//https://zhima.blog.csdn.net/
class EntityTwo : Entity {
    constructor() {

    }

    constructor(name: String) : this(name, 0) {

    }

    //Secondary constructors with different parameters
    constructor(name: String, age: Int) : super(name, age) {
        Log.e("TAG,", "Subclass constructor executed $name===$age")
    }
}

😜 Interface

This is also similar to Java. There is no difference in the use of [interface] definition

The keywords of the modifier class are

  • Abstract / / indicates that this class is abstract
  • final / / indicates that this class is non inheritable. The default attribute is
  • enum / / indicates that this class is an enumeration class
  • open / / indicates that the class is inheritable. The class is final by default
  • Annotation / / indicates that this class is an annotation class

Modifiers for access rights are:

  • private / / access rights - visible only in the same file
  • protected / / access rights - visible in the same file or subclass
  • public / / access permission - visible to all calls
  • internal / / access permission - visible in the same module

After learning and experimental verification, Xiaokong decided to use Java entity classes. Anyway, they have interoperability.

😜 Abstract class / nested class / inner class

Xiaokong will take you directly to see with examples

abstract class EntityThree {
    abstract fun methonOne()
}

//Nested class instance
class One {                  // This is an external class
    private val age: Int = 1
    class Two {             // This is a class inside a class, called a nested class
        fun hello() {

        }

        fun hi() = 3
    }
}
//https://zhima.blog.csdn.net/
//The inner class uses the keyword inner
class Three {
    inner class Four { //This Four class is an inner class
        fun hello() {

        }
        fun hi() = 3
    }
}
//This is a reference example
var one = Three().Four().hello()

😜 Data class

A data class is an entity class in Java
In Kotlin, the data class is decorated with the keyword [data]. It is declared in front of the class class and contains only data. In fact, it is the same thing as the entity class generated by Jason in Java, with several built-in function methods
equals() compare function
toString() format, such as "User(name=John, age=42)"
componentN() functions correspond to attributes, arranged in declaration order
copy() assignment function

When developing in Java, we will use the GsonFormat plug-in to quickly generate the Json data of the interface into an entity.
Now Kotlin has a similar plug-in called [Jason to Kotlin class].
Go to [file setting plugins] to search for installation.
Use: use the shortcut key [Alt+K] (if it does not conflict with other shortcut keys) or open the [Generate...] function box, which contains [Kotlin data classes from JSON]

Being good at using plug-ins can quickly help us improve work efficiency, improve irreplaceable at work, and then realize salary increase.
Let's talk about sealing classes here. For the time being, I didn't expect a more common application environment. The original words of the rookie tutorial are as follows:
A sealed class is used to represent a restricted class inheritance structure: when a value has a limited number of types and cannot have any other types. In a sense, they are extensions of enumeration classes: the value collection of enumeration types is also limited, but there is only one instance of each enumeration constant, while a subclass of a sealed class can have multiple instances of states.
Declare a sealed class and use sealed to decorate the class. A sealed class can have subclasses, but all subclasses must be embedded in the sealed class.
sealed cannot modify interface and abstract class (warning will be reported, but no compilation error will occur)

😜 generic paradigm

Generics is also one of the functions commonly used in our development process. Like Java, Kotlin also uses T to represent generics, which makes the code more robust and solves the unknown steps of type conversion.

//https://zhima.blog.csdn.net/
class Person<T>(t: T) {
    var value = t
}

Use examples are as follows:

//Usage example
var age = Person<Int>(20)
var name = Person<String>("Runoob")
Log.e("TAG,", "Output: $age")
Log.e("TAG,", "Output: $name")

There is no obvious difference between the use of generic constraints and Java

fun <T : Comparable<T>> myHeight(list: List<T>) {
    // ......
}
myHeight(listOf(1,2,3,4))

The above example is correct because Int is a subtype of Comparable

👉 other

📢 Author: Xiaokong and Xiaokong in Xiaozhi
📢 Reprint instructions - be sure to indicate the source: https://zhima.blog.csdn.net/
📢 Welcome to praise 👍 Collection 🌟 Leaving a message. 📝

👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇

Tags: Programming Android Unity kotlin

Posted on Mon, 06 Dec 2021 15:55:24 -0500 by shastry