Preface
Since 2017, when Google defined Kotlin as the official language for Android, there has been an instant upsurge of learning. Learning blogs have sprung up like mushrooms to attack my tiny, helpless heart! It's you, yes, just because you make me stronger and stronger, I thank you for my sparse hair!!! So, get it started! Start our kotlin learning journey from black and bright to barren grass!
My blog (Power)
As a member of the Android development navy, I have looked at the grammar very early in fact. The advantages and disadvantages of the grammar are not stated too much here. If you are not clear or want to know more about it, please do it yourself. Society you spend thirteen mothers In view of the fact that if you are lucky enough to see this article, you must be as familiar with the people we eat as I am, so the younger brother in Android studio's environment configuration here will no longer show off coquettish, after all, all of you here are learning bullies, P in VIP.
Here, at the beginning, I would like to share some of Daniel's links about learning Kotlin, which will help you to avoid picky eating when you eat a hundred meals.
This series is summarized by stepping on the shoulders of giants! May I ask you to take a look at the officer's light spraying _________.
Kotlin Language China
Kotlin - Newbie Course
Kotlin Begins to Advance
Play with Android-kotlin articles
Kotlin Basic Grammar
-
Definition of function
The function uses the keyword fun, and the parameter format is: parameter: type// sum: Function name a,b parameter name, Int parameter type fun sum(a: Int, b: Int): Int {// The back Int is the return value type return a + b }
- It is important to note that if it is public, the return value type must be declared, and if it is a function with no return value (: Unit), it can be omitted.
fun unitFun() : Unit{ println("I am returning a value of Unit A function of, Unit Can be omitted") return // return Unit can be omitted // Or return can be omitted } //Equivalent to fun unitFun(){ println("I am returning a value of Unit A function of, Unit Can be omitted") }
- Variable length parameter function, identified by vararg keyword
fun vars(vararg v:Int){ for(vt in v){ print(vt) } } // test fun main(args: Array<String>) { vars(1,2,3,4,5) // Output 12345 }
-
Constant and Variable
Variable: var < identifier >: < type >= < initialization value >var x: Int = 5 // The system automatically infers that the variable type is Int x += 1 // Variable modifiable
Constant: Val < identifier >: < type > = initialization value >
val a: Int = 1 val b = 1 // The system automatically infers that the variable type is Int val c: Int // Variable types must be provided if they are not initialized at declaration time c = 1 // definitely assigned
Kotlin Basic Data Type
The underlying data types include:
- value type
- Character type
- String type
- Boolean type
- Array type
-
Numbers
The basic numerical types of Kotlin include Byte, Short, Int, Long, Float, Double, etc.
Unlike Java, characters do not belong to numeric types and are a separate data type.type Bit width Byte 8 Short 16 Int 32 Long 64 Float 32 Double 64 -
Characters
Unlike Java, Char in Kotlin cannot be manipulated directly and digitally. Char must be included in a single quotation mark. For example, the common characters `0', `a'.val ch :Char = 1; // Error demonstration val ch :Char = '1'; // Correct Demonstration // Converting character types to numbers val ch :Char = '8'; val a :Int = ch.toInt()
-
Strings
Like Java, String is immutable.//1. Square bracket [] grammar can easily obtain a character in a string, or traverse through a for loop: for (c in str) { println(c) } //2. Supports three quotation marks "" extended strings, and supports multiple lines of strings, such as: fun main(args: Array<String>) { val text = """ //Multiline string //Multiline string """ println(text) // The output has some leading spaces } //3.String can remove redundant blanks by trimMargin(): fun main(args: Array<String>) { val text = """ |Multiline string |Newbie Course |Multiline string |Runoob """.trimMargin() println(text) // Preemptive blank deleted }
String template: That is to say, the result is evaluated in the string by some small pieces of code and merged into the string. Template expressions begin with the dollar sign ($)
fun main(args: Array<String>) { val i = 10 val s = "i = $i" println(s) // The result of evaluation is "i = 10" } //Arbitrary expressions extended with curly brackets: fun main(args: Array<String>) { val s = "runoob" val str = "$s.length is ${s.length}" println(str) // The result is "runoob.length is 6" }
-
Boolean
Boolean is represented by Boolean type, which has two values: true and false.
The built-in Boolean operations are:|| Short circuit logic or && Short circuit logic and ! - Logical nonsense
-
Arrays
Array is implemented with class Array, and there is also a size attribute and get and set methods. Because the use of [] overloads get and set methods, we can easily get or set the values of the corresponding position of the array by subscribing.
There are two ways to create an array: one is to use the function arrayOf(); the other is to use the factory function.fun main(args: Array<String>) { //[1,2,3] val a = arrayOf(1, 2, 3) //[0,2,4] val b = Array(3, { i -> (i * 2) }) //Read Array Content println(a[0]) // Output: 1 println(b[1]) // Output: 2 }
Note: Unlike Java, arrays in Kotlin are invariant.
In addition to the class Array, there are ByteArray, ShortArray, IntArray, and so on, which are used to represent various types of arrays, eliminating the boxing operation, so they are more efficient. They are used in the same way as Array:val x: IntArray = intArrayOf(1, 2, 3) x[0] = x[1] + x[2]
Kotlin's Null Security Design
-
Declarations can be processed for null parameters and null judgments
Add after the type? That is to say null
There are two ways to judge null processing:
The first one is to add after the field!! It means that null exception is thrown like java.
The second is to add after the field, which means that null can be returned without processing.
The third is to add a field after it: to indicate the value returned when the field is null
Of course, if/else is also possible. After null is judged by if, it can be automatically converted to non-null variables.//Type followed by? Represents empty var age: String? = "23" //Throw a null pointer exception val ages = age!!.toInt() //Return null without processing val ages1 = age?.toInt() //age returns - 1 empty val ages2 = age?.toInt() ?: -1
-
Use null types in functions
When a function/method has a return value, if the code in the method uses?. to return a value, then the type of the return value of the method should be followed by a symbol?fun funNullMethod() : Int? { val str : String? = "123456" return str?.length } //Output: 6
Kotlin Type Detection and Automatic Type Conversion
-
We can use the is operator to detect whether an expression is an instance of a certain type (similar to the instanceof keyword in Java)
fun getStringLength(obj: Any): Int? { if (obj is String) { // After type judgment, obj is automatically converted to String type by the system return obj.length } //Here's another way to use it, unlike instanceof in Java. // if (obj !is String){ // // XXX // } // Here, obj is still a reference of type Any return null } //perhaps fun getStringLength(obj: Any): Int? { if (obj !is String) return null // In this branch, the `obj'type is automatically converted to `String'.` return obj.length } //It's even OK. fun getStringLength(obj: Any): Int? { // On the right side of the `&', the `obj'type is automatically converted to `String'.` if (obj is String && obj.length > 0) return obj.length return null }
Kotlin's Interval Expressions
-
Interval expressions are in the form of operators. The rangeTo function is formed by in and! In.
-
Interval is defined for any comparable type, but it has an optimized implementation for integer primitive types. Here are some examples of using intervals:
for (i in 1..4) print(i) // Output "1234" for (i in 4..1) print(i) // Nothing is exported if (i in 1..10) { // Equivalent to 1 <= I & I <= 10 println(i) } // Use step to specify step size for (i in 1..4 step 2) print(i) // Output "13" for (i in 4 downTo 1 step 2) print(i) // Output "42" // Use until functions to exclude end elements for (i in 1 until 10) { // I in [1, 10] excludes 10 println(i) } //Examples of field measurements fun main(args: Array<String>) { print("Cyclic output:") for (i in 1..4) print(i) // Output "1234" println("\n----------------") print("Set the step size:") for (i in 1..4 step 2) print(i) // Output "13" println("\n----------------") print("Use downTo: ") for (i in 4 downTo 1 step 2) print(i) // Output "42" println("\n----------------") print("Use until: ") // Use until functions to exclude end elements for (i in 1 until 4) { // I in [1, 4] excludes 4 print(i) } println("\n----------------") } /* Output results: Cyclic output: 1234 ---------------- Set step size: 13 ---------------- Use downTo:42 ---------------- Use until:123 ---------------- */