Kotlin detailed article notes collation update progress: Kotlin Series – High order functions and Common functions in standard Library (3) Kotlin Series – Advanced Deep Generic Covariant Inversion from Java to Kotlin(4) Koltin series – Coroutines from Recognition to Use in Android (5)
Preface: I have used Kotlin for almost half a year. I read the Introduction of Kotlin in Chinese before, but I always felt that I didn’t have a good understanding of some details when I used it later. I bought a kotlin tutorial and felt good.
1. Member variable & null type
var
用lateinit
Lazy initialization,val
withlazy
Lazy initialization- Type followed by
?
Represents a nullable type that is not followed by a type?
Represents a non-null type- Null type can be used:
? .
Said ifnull
, the returnnull
Otherwise, the return object is returned to continue the logical operation.!!!!! .
Indicates mandatory identification of notnull
Use but it is best to make your own judgment, or else short exceptions? :
Indicates that the current surface isnull
When, return? :
The value behind the
Class X lateinit var mStr:String val X :X by lazy{// val lateinit X()} var name: String? = "" fun a(x: Any): Int { return name? .length ? : 0 } val nullable:String? Val notNull:String = null val notNull:String = null val notNull:String = null Nullable can be used for non-nullable values. .length // Correct, nullable is not null? .length // Correct if nullable is null? .length ? 1: -Copy the code
2. Type conversion
As type conversion as Java type conversion, failure to throw exception as? Safe type conversion, conversion failure return NULL, no exception thrown
Val stub:Childen = parent as Childen // Conversion failure Stub does not return null and will throw an exception val stub:Childen = parent as? Childen // Conversion failure stub can return nullCopy the code
3. The interval
A subclass of ClosedRange, IntRange is most commonly used
- Semi-closed interval..
- Open interval until
- Basic writing:
0.. 100 indicates [0,100] 0 until 100 indicates [0,100) I in 0..100 Check whether the interval is in [0,100]
val range:IntRange = 0.. 1024 //[0,1024] val range_EXCLUSIVE :IntRange = 0 until 1024 //[0,1024) = [0,1023] val emptyRange:IntRange = 0...-1 Emptyrange.isempty () // For (I in range)Copy the code
An array of 4.
Val array: array < type > = arrayOf(type 1, type 2,…..) Basic operations: Array [I] : Enter the ith member array[I] = new type object assigned to the ith member
array.slice()
Interception can be passed ininterval
eg:0.. 10 or 0 until 100
array.joinToString()
Converted intoString
Here are the corresponding parametersSeparator: CharSequence The default is,
–prefix: CharSequence: add prefix default: “” –postfix: CharSequence: add suffix default: “” –limit: Int: interception location (starting at 1 instead of starting from 0) – truncated: be limit after capture, what show – transform: each element processing returned after processing data
Specific examples are shown:
Val arrayOfInt: IntArray = intArrayOf(1,3,5,7) val arrayOfChar: CharArray = charArrayOf('H', 'e','l','l','o','W','o','r','l','d') val arrayOfString: Array<String> = arrayOf(" I ", "yes ", Farmers "code") fun main () {System. Out. Println (arrayOfString. JoinToString (" ")) var I: IntRange = 0.. 100 System.out.println(arrayOfChar.slice(0.. 7)) var array1 = arrayOfString. JoinToString (" ", "prefix", "suffix," 2, "the end", transform = {/ / convert the return @ joinToString it + "transformation"}) var Array2 = arrayOfString. JoinToString (" ", "prefix", "suffix," 3, "the end", transform = {/ / convert the return @ joinToString it + "transformation"}) Println (array1) println (array2)} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- I printed the log is code agriculture [H, e, l, l, o, W, o, R] prefix I convert is to convert after the suffix prefix I convert is to convert code non to convert suffixCopy the code
5. The variable
Val TAG = "STR" is not equivalent to Java public final String TAG = "STR"Copy the code
Public final String TAG = “STR” public final String TAG = “STR
You can see that val is not assignable, but it is not a compiler constant. That is, the compile time is not replaced by a constant, so the later can still be reflected to change! If you want to define a compile-time constant like in Java, public final String TAG = “STR”, you need to use const.
6. Functions and LAMBA expressions
- Anonymous function writing
An essential function is also a member, but it is a block of code
val int2Long = fun(x:Int):Long{
return x.toLong()
}
Copy the code
- Lambda expressions
Var sum = {a:Int,b:Int ->a+b} var sum = {a:Int,b:Int ->a+b} Sum (1,2) or sum.invoke(1,2) simplify: Lambda has only one argument, and the parentheses can be omitted. Lambda has only one argument, which defaults to IT. Functions with input arguments, return values, and parameters can be passed as arguments as function references
Here’s an example:
Public inline fun chararray. forEach(action: (Char) -> Unit): Unit {for element (this) in the action (element)} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- next, Code is called -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - val arrayOfChar: CharArray = charArrayOf (' H ', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd') / / the most basic of call, ForEach (char ->{println(char)}) // simplified //1. Lambda has only one argument which can default to it arrayofchart.foreach ({println(it)}) // 2. Arrayofchar.foreach (){pritln(it)} // 3. ArrayOfChar. ForEach {pritln(it)} // 4. Arrayofchar.foreach (::println) arrayofchar.foreach (::println) arrayofchar.foreach (::println)Copy the code
7. Operators
Unlike Java, Kotlin’s operators allow us to overload. Overloaded functions need to be marked with the operation modifier
Example:
Class TestKotlin(var a:Int) {operator fun minus(I :Int):Int{return a - I}} fun main() { Println (TestKotlin (6) - 5)} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - enter 1Copy the code
There are a lot of operators that you can see in Kotlin Language Chinese
8. Expression (infix branch when, etc.)
- Infix function
A function that takes only one argument and is decorated with infix and does not need an object. Method name (parameter), the direct object method name parameter
// define class Book {infix fun on(palce:String){... } // Use Book() on "My Name"Copy the code
- Branch function
for
The cycle ofin
Click the mousein
So the loop mechanism is actuallyiterator
Mechanism,hasNext()
withNext ()
, determine if there is the next value, if there is, get
MyIntList = MyIntList = MyIntList = MyIntList = MyIntList
class MyIterator(val iterator:Iterator<Int>){ operator fun next():Int{ return iterator.next() } operator fun hasNext():Boolean{ return iterator.hasNext() } } class MyIntList{ private val list = ArrayList<Int>() fun add(int:Int){ list.add(int) } fun remove(int:Int){ list.remove(int) } operator fun iterator():MyIterator{ return MyIterator(list.iterator()) } } fun main() { val list = MyIntList() list.add(1) list.add(2) list.add(3) for (i in list){ println(i) } }Copy the code
2. Skip and terminate loops (continue
withbreak
) withjava
Consistent, skip the current loopcontinue
To terminate the cyclebreak
3. Multi-layer loop nested terminations are used in combination with labels
Outter@for(...) { Inner@while(i<0){if(...) break@Outter} }Copy the code
You can define a tag with an @ tag after the keyword to jump to the corresponding level, for example:
Fun main() {val list = MyIntList() list.add(1) list.add(2) list.add(3) list.add(4) list.add(5) //break for (I in) List) {print(" $I ") while (true) {print(" $I ") break}} println(" ") //break OutSide@for (I in list) {print(" {print $I ") while (true) (" $I ") break @ OutSide}}} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- print -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 1 2 1 2 3 4, 3, 4, 5 5 1Copy the code
If else branch expressions, etc., differ from Java in that they are expressions that can be used to assign values, with the last row of data equal to the data of the return
fun compare():Int{
val i = 10
if (i == 10 ) 1 else 0
}
Copy the code
9. Exception catching
Unlike Java, it is also an expression, and the last row of data is treated as the value to be returned.
But note the following:
return try{x/y}catch(e:Exception){0}finally{... }Copy the code
After the try is executed, the catch is executed, finally is executed, and the value is returned. (If x/y is returned normally, throw returns 0)
10. Parameters (named, variable length, default)
All parameters have one thing in common: if there is ambiguity when passing a parameter, you need to use a named parameter
- The default parameters
fun sum(arg1:Int = 3,arg2:Int = 2) = arg1+arg2
Copy the code
- Named parameter (vararg variable name: type)
Append parameters to function arguments
fun sum(arg1:Int,arg2:Int) = arg1+arg2
sum(arg1=2,arg2=3)
Copy the code
- Variable-length argument
A parameter can take multiple values. Unlike Java, which does not have to take the last parameter, Kotlin supports named functions, so it can be placed anywhere in the parameter.
Fun hello(vararg ints:Int,string: string){ints.foreach (::println)} use: hello(1,2,3,4,string=" hello ")Copy the code
- Spread the Operator (
* the variable name
)
Application scenario: Only Array can be expanded. It is only used as an argument of a variable length parameter list and cannot be overloaded. It is not an operator
Fun hello (double: double,vararg ints:Int,string: string){ints.foreach (::println)} use: Val array = intArrayOf(1,2,3,4) hello(3.0,*array,string=" hello ")Copy the code