Basic grammar of kotlin language

Time:2021-7-28

Kotlin is a static programming language for modern multi platform applications, which was developed by   JetBrains development, which is a new language running on the JVM; Kotlin language is the optimization and encapsulation of Java language. There are many similarities in syntax, and they can call each other; Kotlin language can be used in five scenarios: Web front-end development, web back-end development, Android mobile end development, server script development and desktop game development; Therefore, it is necessary to learn kotlin language. Let’s explore its grammar.

**1. Variables and output of kotlin language
**

**1. 1 variable
**

During the running process of the program, some temporary data may be generated at any time. The application program saves these data to some memory units, which are called variables; Variables include variable name, variable type and variable value; Its function is to store a data and give the data a name to facilitate developers to use the variable. It is similar to a container; The variables declared by VaR are readable and writable, and the variables declared by Val are only readable.

There are 8 common variable types

Byte    Stored value range integer – 128 ~ 127
Short    Stored value range integer – 32768 ~ 32767
Int    Stored value range integer – 2147483648 ~ 2147483647
Long stored value range integer – 9223372036854775807 ~ 9223372036854775807
Float    The stored value range is decimal, and the decimal point can be accurate to 6 digits
Double    The stored value range is decimal, and the decimal point can be accurate to 15-16 digits
String    Store the string of value range. Any string enclosed in “” double quotation marks can be saved
Boolean stores two Boolean values, which are true and false

The following code is used to explicitly declare the variable types in 8, for example:

PS: code written on Android studio

var b:Byte = 123
 var s:Short = 32766
 var i:Int = 2
 var l:Long = 46L
 var f:Float = 47F
 var d:Double = 90.478326548359783
 Var S2: String = "hello"
 var b2:Boolean = false

Some of the above types are easily inferred by the compiler and can be declared implicitly

/**
 *Compiler infers int type
 */
 var i2 = 2
 /**
 *The compiler infers long
 */
 var l2 = 46L
 /**
 *Compiler infers float type
 */
 var f2 = 47F
 /**
 *The compiler infers double
 */
 var d2 = 90.478326548359783
 /**
 *The compiler infers a string type
 */
 Var S4 = "hello"
 /**
 *The compiler infers a boolean type
 */
 var b3 = false

**1. 2 output
**

Kotlin’s output is actually the output of some content on the console, that is, printing. The following code examples are listed:

/**
 *Output Hello on the console without line feed
 */
 Print ("hello")
 /**
 *Output Hello and line feed on the console
 */
 Println ("hello")

**2. Functions and functional expressions
**

2. 1 function

Function is the unit that the computer executes commands. It describes the behavior. Generally, it refers to all the behaviors or actions that can be executed by the object; It can also be understood that the functions in the computer are small fragments of program execution, which can be organically combined to complete business functions; It can have a return value or no return value, can have parameters or no parameters, and is declared with the fun keyword; Here is an example:

/**
 *This is a function with no parameters and no return value
 */
 fun function1() {
 Println ("this is a function with no parameters and no return value")
 }
 /**
 *This is a function with 2 parameters and no return value;
 *The two parameters are string and int types respectively
 */
 fun function2(s: String,i: Int) {
 Println ("this is a function with 2 parameters and no return value")
 }
 /**
 *This is a function with no parameter and return value;
 *The return value type is int
 */
 fun function3():Int{
 Println ("this is a function with no parameters and a return value")
 return 1
 }
 /**
 *This is a function with 2 parameters and return value;
 *The two parameters are string and int types respectively;
 *The return value is int
 */
 fun function4(s: String,i: Int):Int{
 Println ("this is a function with 2 parameters and return value")
 return 1
 }

2. 1 functional expression

Functional expression is a simplification of a function with a small amount of code, similar to lambda expression in Java, that is, when there is only one statement in the function and it is a return value statement, you can omit the return keyword to write a functional expression; Here are some examples where functions can be written as functional expressions.

(1) A functional expression with the fun keyword.

/**
 *   Defines a function with 2 parameters and a return value of 1   function(x:Int,y:Int)
 */
 fun function(x:Int,y:Int):Int = 1

(2) A functional expression without the fun keyword.

/**
 *Here, it can be understood as defining the function name as I,
 *Two int type parameters X and y,
 *Function with return value of int type and return value of X * y
 */
 var i = {x:Int,y:Int -> x*y}
 var result = i(3,5)
 println(result)
 /**
 *Here is the same understanding as defining I function
 */
 var j:(Int,Int)->Int = {x,y ->x*y}
 var result2 = j(3,5)
 println(result2)

**3. String
**

3. 1 string template

String literals can contain template expressions, that is, small pieces of code that evaluate and merge the results into the string; The template expression starts with the dollar sign $, or any expression enclosed by curly brackets ${}; Here is an example:

var i:Int = 4
 Var s: String = "Park"
 /**
 *I evaluates to 4 and merges 4 into a string
 */
 Var S2: String = "I made ${I} yuan today"
 /**
 *S find the value "Park" of string type and merge the "Park" into the string
 */
 Var S3: String = "if it doesn't rain tomorrow, we'll go to ${s}"

**3. 2 string comparison
**

The string comparison mentioned here is to compare whether the contents of the two strings are equal, rather than whether the two strings are the same object. It can be written in three ways. Here is an example:

var s4:String = "hello World"
 var s5:String = "hello world"
 /**
 *B is false
 */
 var b:Boolean = s4 == s5
 /**
 *B2 is false
 */
 var b2:Boolean = s4.equals(s5)
 /**
 *B3 is true, and the parameter is true, indicating that it is not case sensitive
 */
 var b3:Boolean = s4.equals(s5,true)

**4. Null value of kotlin
**

Null in kotlin, which is also a value, means that there is no data and nothing; The following is an example of a variable of type string:

/**
 *Add a?, after the type, Indicates that null variables of this type are allowed
 */
 var s:String? = null
 Var S2: String = "hello"
 /**
 *The value of S3 here is null
 */
 var  s3:String = s2 + s

5. When expression

In Java, we are more used to usingswitch/caseMode, butswitch/caseThe types of support are very few, and there are some limitations in use; In kotlin, when expression is introduced, which can completely replace switch / case, and there are many new features; When expression is based on a given condition and executes whatever condition is satisfied; The following is the when in different cases   Expression example.

(1) General usage of when expression

var num:Int = 3
 when(num) {
 /**
 *Here, if 3 is satisfied, the statement of 3 will be executed. After execution, the loop will jump out, which is equal to
 *Case 3: break in Java
 */
 3 - > println ("current number" + Num)
 2 - > println ("current number" + Num)
 1 - > println ("current number" + Num)
 /**
 *Else in this is equivalent to default in Java switch / case
 */
 Else - > println ("the current number is not 1, 2 or 3")
 }

(2) The when expression can also be written as an argument auto transformation type

var appCompatActivity: AppCompatActivity = MainActivity()
 when(appCompatActivity) {
 Is mainactivity - > println ("the current object is of type mainactivity")
 Is test - > println ("the current object is TETS type")
 Else - > println ("the current object is of another type")
 }

(3) When expressions can also be written as types without arguments

Var S2: String = "hello"
 var i2:Int = 3
 when {
 S2 = = "ha ha" -> println ("the content of S2 is ha ha")
 I2 = = 3 - > println ("the value of I2 is 3")
 Else - > println ("other output")
 }

(4)when   An expression can also have a return value, and return is not allowed   keyword

var num2:Int = 3
 /**
 *1. The return value type of each execution statement in the when expression must be consistent, that is, num2 and 0 are int types;
 *2. The variable type receiving the return value must be consistent with the type of the return value of the execution statement in when, that is, the types of num2 and result are consistent
 */
 var result:Int = when(num2) {
 3 -> {
 Println ("the current return value is 3")
 num2
 }
 else -> {
 Println ("the current return value is 0")
 0
 }
 }

6、Range   and   for   loop

6、1 Range

Range is a new expression added by kotlin relative to Java. It represents the range of values, which is similar to the interval in mathematics. The number in the interval must be of type int. It can be written in four ways:

(1) Numerical value 1.. numerical value 2, indicating the range from numerical value 1 to numerical value 2 (including numerical value 1 and numerical value 2);

(2) A1 unti A2, indicating the range from A1 to A2-1 (including A1 but not A2);

(3) A2 downto A1, indicating the reverse order of A1.. A2 (A2 > A1);

(4) A1.. A2 step n means that the data is retrieved from A1 and every n numbers until the number is not within the range of A1 and A2;

The following is an example of its syntax:

/**
 *Interval [1,10], excluding 10
 */
 var ia:IntRange = 1 until 10
 /**
 *Interval [1,10], containing 1 and 10
 */
 var ia2:IntRange = 1 .. 10
 /**
 *Flashback interval [10,1], including 10 and 1
 */
 val intRangeReverse = 10 downTo 1
 /**
 *Interval step size fetching: fetching from interval [1,10]. Starting from 1, take out one every three numbers. Finally, this number is not
 *Even if the interval is taken, the number stored in the final interval is 1,4,7,10
 */
 var ia3 = 1 .. 10 step 3
 /**
 *Reverse the number of the interval [1,10], that is, [10,1]
 */
 var ia4 = ia2.reversed()
 /**
 *Get quantity in interval [1,10]
 */
 var num:Int = ia2.count();

6、2   For loop

The function of the for loop is to traverse the elements of a set and get them out for use one by one. The keyword in is used in the parentheses of the for loop.

The following are examples:

/**
 *Define an array of int type
 */
 var ia:IntArray = intArrayOf(1,2,3,4,5)
 /**
 *Traversing an array of int type with a for loop
 */
 for (i in ia) {
 println("i = " + i)
 }

7、List   and   Map

7、1 List

List is a list of stored data, similar to list in Java; The function to construct the list is as follows:

(1) Listof(), indicating the construction of an empty list;

(2) Listof (a), indicating that a list with data is constructed;

(3) Listof (a, B, C,…) represents a list for constructing multiple data

The following code is an example:

/**
 *Construct a list without data
 */
 var list: List<String> = listOf()
 /**
 *Construct a list with only one data
 */
 var list2: List<String> = listOf("A")
 /**
 *Construct a list of multiple data
 */
 var list3: List<String> = listOf("A", "B", "C")

7、2 Map

Map   Similar to a dictionary, words have an index, and the index corresponds to specific content, and the map in Java   similarThe method of constructing map is as follows:

(1) Mapof(): this function returns an immutable map collection
(2)mutableMapOf():   This function returns a mutablemap collection that is mutable
(3)hashMapOf():   This function returns a variable HashMap collection
(4) Linkedmapof(): this function returns a variable LinkedHashMap collection
(5)sortedMapOf():   This function returns a mutable treemap collection
(6) Treemap < K, V > (): this function returns a variable treemap set

Here is an example of constructing a map with code:

val map = mapOf("Android" to 56, "Kotlin" to 78, "C" to 74)
 Println ("the actual type of mapof() is ${map. Javaclass}")
 val mutableMap = mutableMapOf("Android" to 56, "Kotlin" to 78, "C" to 74)
 Println ("the actual type of mutablemapof() is ${mutablemap. Javaclass}")
 val hashMap = hashMapOf("Android" to 56, "Kotlin" to 78, "C" to 74)
 Println ("the actual type of hashmapof() is ${HashMap. Javaclass}")
 val linkedMap = linkedMapOf("Android" to 56, "Kotlin" to 78, "C" to 74)
 Println ("the actual type of linkedmapoof() is ${linkedmap. Javaclass}")
 val treeMap = sortedMapOf("Android" to 56, "Kotlin" to 78, "C" to 74)
 Println ("the actual type of sortedmapof() is ${treemap. Javaclass}")
 var treeMap2 = TreeMap<String,Int>()
 treeMap2["Android"] = 56
 treeMap2["Kotlin"] = 78
 treeMap2["C"] = 74
 Println ("the actual type of treemap < string, int > () is ${treemap2. Javaclass}")

The data extraction of map is traversed one by one by using the for loop, which is written as follows:

(1)for (entry in map.entries) {  }, For in traversal, traversing the entry;

(2) For (key in map. Keys) {}, traverse the key, and then obtain the value through the key;

(3) For ((key, value) in map) {}, for in traversal, key and value traversal at the same time;

(4)map.forEach {  }, Foreach lambda expression traversal;

The following code is an example:

/**
 *For in traversal, traversing the entry
 */
 for (en in map.entries) {
 println("${en.key}: ${en.value}")
 }
 /**
 *Traverse the key, and then obtain the value through the key
 */
 for (key in map.keys) {
 println("$key: ${map[key]}")
 }
 /**
 *For in traversal, key and value traversal at the same time
 */
 for ((key, value) in map) {
 println("$key: $value")
 }
 /**
 *Foreach lambda expression traversal
 */
 map.forEach {
 println("${it.key}: ${it.value}")
 }

8. Conversion between string and number

8、1 Convert to number string

The prerequisite for successful conversion of a string into a number is that the contents of the string must be numeric and cannot have other symbols. Its conversion method is: String object. Toint(), for example:

var s:String = "123"
 /**
 *It can be converted to a number here because the contents of s are numeric values
 */
 var num:Int = s.toInt()
 
 var s2:String = "12s"
 /**
 *Error will be reported;
 *It can not be converted into numbers here, because the contents of S2 are not all numeric values and contain s characters
 */
 var num2:Int = s2.toInt()

8. 2 convert numbers to strings

There are no restrictions on converting a number to a string. Its conversion method is: int type object. Tostring(), as an example:

 var num3:Int = 4
 var s3:String = num3.toString()
 println("s3 = " + s3)

9. Abnormal

In kotlin program, errors may occur in various situations that the programmer did not expect, or in an environment beyond the programmer’s control. For example, if you try to open a nonexistent file, an error will run in the program; To prevent this, we must refer to the exception class in the kotlin language; All exception classes in kotlin are descendants of throwable class. Each exception has a message, stack backtrace information, and an optional reason.

The catch exception in kotlin is composed of try {} catch (E: exception) {} finally {} statements. At least one of catch and finally must exist. Finally is not necessary and can be written or not. Regardless of whether the program catches an exception, the code block in finally will be executed, and the catch code block handles exceptions; The following is a code example:

var s: String? = null
 try {
 /**
 *S here is a null value, which will cause a null pointer exception
 */
 var b:Boolean = s.equals("123")
 } catch (e: Exception) {
 Println ("catch code block executed because s is null")
 }finally {
 Println ("finally code block will be executed whether s is null or not")
 }

This article ends here. Due to the limited technical level, there will inevitably be errors in the article. You are welcome to criticize and correct. In addition, the demo address is attached:https://github.com/Yubao1/Kot…

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]