Kotlin learning notes basic syntax, kotlin learning notes
Kotlin Study Notes (2)-basic syntax
Kotlin learning notes Series
Kotlin Study Notes (1)-Overview, learning curve, development tools, references
1. Basic syntax definition package
The package declaration should be at the top of the source file:
package hard.uistudy.dai.uifinaltest.main.view.fragmentimport android.os.Bundleimport android.support.v4.app.Fragment
Define functions
Functions with two Int parameters and Int returned:
fun addNumber(a : Int, b: Int) : Int { return a + b }
Automatically deduce an expression as the function body and return value type:
fun addNumber(a: Int, b: Int) = a + b
The function returns meaningless values:
fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}")}
Unit return type can be omitted:
fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}")}
Define Variables
A local variable with a single value (read-only cannot be written ).Val modifier:
Val a: Int = 5 // assign a value immediately val text = "aaa" // automatically deduce the type
Variable (readable and writable), useVar modifier:
Var B = 5 // automatically infer that the 'int' type B = 6/*** is not assigned a value for the time being. lateinit cannot be used for null attributes or java basic types, lateinit can only modify var */lateinit var open: String... open = "aaa" ''' top-level variable: ''' val PI = 3.14var x = 0fun incrementX () {x + = 1}
Note
Like Java, kotlin also supports row and block annotations.
// This is a line comment/* This is a multiline block comment. */
Use string Template
Use the $ symbol
Var a = 1 // simple name in the template: val s1 = "a is $ a" a = 2 // any expression in the template: val s2 = "$ {s1.replace (" is "," was ")}, but now is $"
Use conditional expressions
fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b }}
Use if as the expression:
fun maxOf(a: Int, b: Int) = if (a > b) a else b
Use null and null Detection
When the value of a variable may be null, you must add? To identify the reference as null.
IfIf the text content is not a number, return null:
fun parseInt(string: String) : Int?{ return if (string.toInt() != null) string.toInt() else null }
Use a function that returns NULL values:
fun getProduct(str1: String, str2: String){ val x = parseInt(str1) val y = parseInt(str2) if (x != null && y != null){ print(x + y) } else{ println("either '$str1' or '$str2' is not a number") } }
Or separate analysis
//...... If (x = null) {println ("Wrong number format in arg1: '$ arg1'") return} if (y = null) {println ("Wrong number format in arg2: '$ arg2'") return} // After null detection, x and y are automatically converted to non-null println (x * y)
Use Type detection and automatic type conversion
The is operator checks whether an expression is an instance of a certain type. If an unchangeable local variable or attribute has been determined to be of a certain type, the detected branch is directly used as this type, and no need to display the conversion:
Fun getStrigLength (obj: Any): Int? {If (obj is String) {// 'obj 'is automatically converted to 'string' return obj within this condition branch. length} // after leaving the type detection branch, 'obj 'is still 'any' type return null}
Or
Fun getStringLength (obj: Any): Int? {If (obj! Is String) return null? // 'Obj 'is automatically converted to 'string' return obj. length} in this branch}
Even
Fun getStringLength (obj: Any): Int? {// 'Obj 'is automatically converted to 'string' type on the right side of' & 'if (obj is String & obj. length> 0) {return obj. length }? Return null}
Use for Loop
val list = arrayListOf("1","2","3","4") fun printList(){ for (item in list){ print(item) } }
Or
val list = arrayListOf("1","2","3","4") fun printList(){ for (index in list.indices){ print("$list at $index value is ${list[index]} " ) } }
Use a While loop
val list = arrayListOf("1","2","3","4") fun printList(){ var index = 0 while (index < list.size){ print("$index,${list[index]}") index++ } }
Use When Loop
fun printList(index : Int) : String = when (index ){ 1 -> "$index value is 1" 2 -> "$index value is 2" 3 -> "$index value is 3" 4 -> "$index value is 4" else -> "null" }
Range)
Use the in operator to check whether a number is within the specified range:
val startIndex = 10 val endIndex = 20 fun sortNum(){ if (startIndex in 1.. endIndex){ print("$startIndex is in range") } }
Interval iteration:
fun sortNum(){ for (index in startIndex .. endIndex){ print(index) } }
Series iteration
// Skip the three elements for (index in startIndex .. endIndex step 3) {print (index)} // traverses in descending order. Three elements for (index in endIndex downTo startIndex step 3) are skipped each time ){}
Checks whether a number is out of the specified range:
val list = listOf("a", "b", "c")if (-1 !in 0..list.lastIndex) { println("-1 is out of range")}if (list.size !in list.indices) { println("list size is out of valid list indices range too")}val list = listOf("a", "b", "c")?if (-1 !in 0..list.lastIndex) { println("-1 is out of range")}if (list.size !in list.indices) { println("list size is out of valid list indices range too")}
Use set
Perform iteration on the set:
val lists = listOf("a", "b", "c") fun sortList(){ for (item in lists){ print(item) } }
Use the in operator to determine whether the set contains an instance:
val lists = listOf("a", "b", "c") fun sortList(){ when{ "a" in lists -> print("a") "b" in lists -> print("b") } }
Filter and map sets using lambda expressions:
Val lists = listOf ("aa", "AB", "ac", "1", "2", "3", "4") fun sortList () {lists. filter {it. startsWith ("a")} // filter elements starting with. sortedBy {it} // sort. map {it. toUpperCase ()} // converts the string to uppercase. forEach {print (it)} // traverses the output string}
Create basic classes and their instances
Val rectangele = Rectangle () // The new Keyword val triangle = Triangle () is not required ()