1.1 Get and SET processing
There are some formatting differences from Java:
-
Getter/setter functions have special keywords get and set
-
Getter/setter functions are located below the variables declared by var
-
The setter function argument is value
In addition to this, there is something called field. This thing is called a “Backing Field.” This field is not visible to the person encoding it, but is automatically applied to getters and setters, so it is named the “Backing Field.” In Kotlin, it is equivalent to a variable inside each var.
class User { var name = "Mike" 👇 get() { return field + " nb" } 👇 👇 set(value) { field = "Cute " + value } } Copy the code
1.2 Constants in Kotlin
1.1.1 Static Constants
- Companion object
There is no static keyword in Kotlin. If you want to declare static methods or properties in a class, place them in a Companion Object.
class Constants { companion object { val FOO = “foo” } }
-
const val
Conditions of use
- As a top-level attribute,
companion object
Attributes, orobject
attribute - Only String or primitive types can be modified
- You cannot customize getters
Class Constants {companion object {const val FOO = “FOO”}} // Static Constants
- JvmField
To remove const, add the JvmField annotation to FOO
Class Constants {companion object {@jVMField val FOO = FOO () // FOO () is for the purpose of specifying that there is no constraint on primitive type}}
1.1.2 Top – Level
If a class is only used to load constants, then we can safely "discard the class and the Companion Object" and use Kotlin's file-level attributes (top-level attributes) directly in kt filesCopy the code
const val FOO = “foo”
Generate the corresponding Java code (probably the code you write when using Java)
public final class ConstantsKt {
@NotNull
public static final String FOO = "foo";
}
Copy the code
1.3 NULL check Mechanism
Kotlin’s empty safety design for the declaration can be empty parameters, in the use of empty judgment processing, there are two processing methods, after the field plus!! Throw an empty exception, as in Java, followed by? Do not do processing return value null or cooperate? : Short judgment processing
// Type after? Var age: String? Val ages = age!! .toint () // Returns null val ages1 = age? .toint () // return -1 if age is null val ages2 = age? .toInt() ? 1: -Copy the code
1.4 String Templates
$represents a variable name or value
$varName represents the variable value
${varname.fun ()} denotes the return value of the variable’s method:
1.5 range
Interval expressions are given by operators of the form.. The rangeTo function is complemented by in and! The in formation.
An interval is defined for any comparable type, but for integer primitive types, it has an optimized implementation. Here are some examples of using ranges:
1.6 Delayed Initialization
Here’s what it says:
🏝 ️lateinit var view: View
Copy the code
Lateinit means: tell the compiler I can’t initialize it the first time, but I’ll definitely do it before I use it.
All it does is tell the IDE not to check initialization and report errors for this variable. In other words, by adding the LateInit keyword, you initialize the variable on your own and the compiler doesn’t check it for you.
1.7 Classes and objects
1) The method of writing an inheritance of a class is extends in Java, whereas Kotlin uses:, but: represents both inheritance and Java's implement. 2) Use the 'is' keyword for' type judgment ', directly for strong call? The 'as' keyword can be usedCopy the code
1.8 Implementation of deferred initialization
Lateinit is only used for var, and lazy is only used for val
Lazy is applied to the singleton mode (if-null-then-init-else return), and the delegate method is executed if and only if the variable is called for the first time.
Lazy () is a function that takes a lambda and returns an instance of lazy
that can be used as a delegate to implement the delay attribute: The first call to get() executes the lambda expression passed to lazy() and records the result, and subsequent calls to get() simply return the result of the record.
val lazyValue: String by lazy {
println("computed!")
"Hello"
}
fun main(args: Array<String>){println(lazyValue) println(lazyValue)} Prints results computed! Hello HelloCopy the code
1.9 Use of the by keyword
In Kotlin, the by keyword is used to simplify the implementation of proxy (delegate) mode. It can not only be used as a class proxy, but also can be used as a class attribute, listening for attribute changes.
-
Class proxy class
-
Property lazily loads lazy
-
Observable property: Delegates. Observable (extension: Delegates. Vetoable)
-
Custom listening property changes ReadWriteProperty
-
Property of non-null strength: Delegates. NotNull ()
-
The Map value maps to the class attribute Map
private val model: NameViewModel by viewModels() Copy the code
2.1 Kotlin creates an array
(1) Kotlin uses Array to represent arrays.
(2) [] can be used to access elements of an Array. [] is overloaded with operators that call setter and getter methods of the Array class
2.1.1 Creating an empty Array
val arrayEmpty = emptyArray<String>()
Copy the code
2.1.2 Create an empty array of specified length
val array1 = arrayOfNulls<Int>(5) for (i in 0.. 4) { array1[i] = i }Copy the code
2.1.3 Creating an array of specified length
val array4 = Array(5, {0})
Copy the code
Initialize an array of length 5 with 0 elements
val array5 : Array<String> = Array(5, {""}) for (i in 0.. 2) { array5[i] = i.toString() }Copy the code
Initialize the length is 5, array elements are “”, and for the former three elements array assignment,” 0 “, “1”, “2”, “”,” “
2. 1.4 Create an array using kotlin encapsulation
val array1 = arrayOf(1, 2, 3, 4)
val array2 = intArrayOf(1, 2, 3, 4)
Copy the code
2.1.5 Associated Objects
If you need to write a function (for example, a factory method) that can be called without an instance of a class but needs to access the inside of the class, you can write it as a member of the object declaration within the class.
More specifically, if you declare a companion object within your class, you can access its members, using only the class name as the qualifier.
2.1.6 Usage of as vs IS
2.1.6.1 Usage of IS
The IS operator provided by the KOtlin API is similar to the use of the instanceof keyword in Java. The IS operator checks whether an object is compatible with a particular type (compatible: the object is of that type, or a derived class). It is also used to check whether an object (variable) belongs to a data type (such as Int, String, Boolean, etc.). ! The IS operator is its negative form.
Val mAccount = “println(mAccount is String)
2.1.6.2 Usage of AS
The AS operator is used to perform explicit type conversions of reference types. If the type to be converted is compatible with the specified type, the conversion succeeds; If the types are incompatible, use as? The operator returns the value null. In Kotlin, a parent class is prohibited from being converted to a child type. The AS operator is used to perform explicit type conversions of reference types. If the type to be converted is compatible with the specified type, the conversion succeeds; If the types are incompatible, use as? The operator returns the value null. In Kotlin, a parent class is prohibited from being converted to a child type.
open class Fruit open class Apple(name: String) : Fruit() // val mApple = Apple(” Apple “) // println(mFruit as Apple)
2.1.7 Go through the number groups
Val array7 = Array (4, {I – > I * I}) / / 0,1,4,9,16
For (item in array7) {println(item)}
For (item in array7.indices) {println(item)}
Iterator () for (item in it. Iterator ()) {println(item)}
Var it1 = array7.iterator() it1.forEach {println(it)}
ForEach {println(it)} forEach {println(it)}
There are three main categories:
- List: stores repeated values, which are sorted by Index.
- Set: stored in a
Set
The contents are unique and unordered. - Map* : stores the Map in key-value mode. The Value can be obtained by using a Key.
Note: Although Map does not inherit from Collection, it is still generalized within the Collection function.
All three categories are immutable, meaning that once a List Set Map is created, its contents cannot be modified. However, there is an individual type that can be modified from the original type:
-
MutableList: List that can be modified.
-
MutableSet: a Set that can be modified.
-
MutableMap: a Map that can be modified.
1.6 Kotlin and or not operation
-
And: indicates the bitwise and. Returns 1 when both digits are 1.
-
Or: bitwise or. If one of them is 1, you can return 1.
-
Inv: indicates bitwise non. Unary operator that inverts every bit of the operand, including the sign bit.
-
Xor: xOR by bit. .
-
SHL: left-shift operator.
-
SHR: right shift operator.
-
Ushr: Unsigned right-shift operator.