In this section, I’ve prepared some essential Kotlin basics for you. When learning a language, we first need to learn what kind of data it has, and how its array, collection and method are sub-, because these are the first step when we start a new language, but also the basis of the foundation.

So, to get you up to speed in this lesson, I’m going to use the analogy between Kotlin and Java, which is one of the time-tested lessons of learning other languages quickly as an experienced developer. Just like kung fu, kung fu practitioners often use existing internal skills to quickly master a new kung fu. For Android partners, the use of Java for so many years is our internal skills, so HERE I will take you to quickly start Kotlin with the help of existing internal skills.

Kotlin base type

Kotlin’s basic numeric types include Byte, Short, Int, Long, Float, Double, and so on. Unlike Java, a character is not a numeric type, but a separate data type.

For integers, there are four types with different sizes and value ranges

type A wide The minimum value The maximum
Byte 8 – 128. 127
Short 16 – 32768. 32767
Int 32 – 2147483648 (231) 2147483647 (231-1)
Long 64 – 9223372036854775808 (263) 9223372036854775807 (263-1)

For floating-point numbers, Kotlin provides Float and Double types

type A wide
Float 32
Double 64

Go to Kotlin’s array

Arrays are represented in Kotlin using the Array class, which defines the get and set methods (which convert to [] according to operator overloading conventions) and the size property, as well as some other useful member methods:

class Array<T> private constructor() {
    val size: Int
    operator fun get(index: Int): T
    operator fun set(index: Int, value: T): Unit
    
    operator fun iterator(a): Iterator<T>
    / /...
}
Copy the code

Kotlin array creation techniques

Create an array using the arrayof method

We can use the library method arrayOf() to create an array and pass the element values to it, so arrayOf(1, 2, 3) creates an array [1, 2, 3].

Create an array using the ArrayOfNulls method

The library method arrayOfNulls() can also be used to create an array of a specified size with all elements empty.

Dynamically creating an array

With the Array constructor, which takes an Array size and a method argument, methods used as arguments can return the initial value of each element of the given index:

/ / create a Array < String > initialized to [" 0 ", "1", "4", "9", "16"]
val asc = Array(5) { i -> (i * i).toString() }
asc.forEach { println(it) }
Copy the code

As mentioned above, the [] operator represents calling the member methods get() and set().

In Kotlin, arrays are invariant. This means Kotlin won’t let us assign to Array to prevent possible runtime failures.

Primitive array

Kotlin also has special classes for representing arrays of native types with no boxing overhead: IntArray, ByteArray, ShortArray, and so on. These classes do not inherit from Array, but they share the same set of method attributes. They also have corresponding factory methods:

// Create arrays with intArrayOf, floatArrayOf, doubleArrayOf, etc
val x: IntArray = intArrayOf(1.2.3)
println("x[1] + x[2] = ${x[1] + x[2]}")
Copy the code
// An integer array of size 5 and value [0, 0, 0, 0, 0]
val arr = IntArray(5)

// For example, initialize an array value with a constant
// An integer array of size 5 and values [42, 42, 42, 42, 42]
val arr = IntArray(5) { 42 }

// For example, use lambda expressions to initialize values in arrays
// An integer array of size 5 and value [0, 1, 2, 3, 4] (value initialized to its index)
var arr = IntArray(5) { it * 1 }
Copy the code

Kotlin array traversal technique

Array traversal

for (item in array) {
    println(item)
}
Copy the code

Iterate over a group of numbers with an index

for (i in array.indices) {
    println(i.toString() + "- >" + array[i])
}
Copy the code

Iterate over elements (with indexes)

for ((index, item) in array.withIndex()) {
    println("$index->$item")}Copy the code

ForEach traverses the array

array.forEach { println(it) }
Copy the code

The forEach enhanced version

array.forEachIndexed { index, item ->
    println("$index:$item")}Copy the code

Go to Kotlin’s collection

The Kotlin library provides a set of tools for managing collections, which are sets of items of variable (possibly zero) quantity that are important to solving problems and are often used.

  • A List is an ordered collection of elements that can be accessed by an index (an integer reflecting their position). The element can appear multiple times in the list. An example of a list is a sentence: there is a set of words, the order of the words is important, and the words can be repeated.
  • A Set is a Set of unique elements. It reflects the mathematical abstraction of a set: a set of objects without repetition. In general, the order of elements in a set is not important. For example, an alphabet is a set of letters.
  • A Map (or dictionary) is a set of key-value pairs. Keys are unique, each key maps to exactly one value, and the value can be repeated.

The variability and immutability of sets

So what are the mutability and immutability of Kotlin sets? There are two kinds of sets in Kotlin, one can be modified and one can’t be modified.

Immutable set

val stringList = listOf("one"."two"."one")
println(stringList)

val stringSet = setOf("one"."two"."three")
println(stringSet)
Copy the code

Variable set

val numbers = mutableListOf(1.2.3.4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
println(numbers)
Copy the code

It is easy to see that every immutable set has a corresponding mutable set, that is, a set prefixed by mutable.

Collection sorting

Kotlin provides a powerful set sorting API. Let’s take a look at it:

val numbers = mutableListOf(1.2.3.4)
// Randomly arrange the elements
numbers.shuffle()
println(numbers)
// Sort from small to big
numbers.sort()
// Sort, from largest to smallest
numbers.sortDescending()
println(numbers)

// Define a Person class with name and age attributes
data class Language(var name: String, var score: Int)

val languageList: MutableList<Language> = mutableListOf()
languageList.add(Language("Java".80))
languageList.add(Language("Kotlin".90))
languageList.add(Language("Dart".99))
languageList.add(Language("C".80))
// Use sortBy to sort, suitable for single condition sort
languageList.sortBy { it.score }
println(languageList)
// Use sortWith to sort, suitable for multi-condition sort
languageList.sortWith(compareBy(
        // The it variable is an implicit argument in lambda
        { it.score }, { it.name })
)
println(languageList)
Copy the code

Go to Kotlin’s Set and Map

/**set**/
val hello = mutableSetOf("H"."e"."l"."l"."o")// Automatically filter repeating elements
hello.remove("o")
// Add and subtract the set
hello += setOf("w"."o"."r"."l"."d")
println(hello)

/**Map
      
        is not a successor of the Collection interface; But it is also a collection type of Kotlin **/
      ,>

val numbersMap = mapOf("key1" to 1."key2" to 2."key3" to 3."key4" to 1)

println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")
if ("key2" in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")
if (1 in numbersMap.values) println("1 is in the map")
if (numbersMap.containsValue(1)) println(" 1 is in the map")
Copy the code