Seven Kotlin development skills you need to know

Get into the habit of writing together! This is the 15th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

1. for loop in kotlin

  • The first..
for (i in 0..5) {
    println(i)
}
复制代码

正序Output: 0 1 2 3 4 5, which is a left-closed right-closed interval

  • the seconduntil
for (i in 0 until 5) {
    println(i)
}
复制代码

正序Output: 0 1 2 3 4, which is a left-closed right-open interval

  • the thirddownTo
for (i in 5 downTo 0) {
    println(i)
}
复制代码

倒序Output: 5 4 3 2 1 0, which is a left-closed right-closed interval

  • the fourthstep

This is with a step size, such as:

for (i in 0 until 5 step 2) {
    println(i)
}
复制代码

Output: 0 2 4, you can see that the step size is set to 2 and the output is every 2

  • Fifth Middle Schoolzip
for((i, j) in (1..5).zip(5..10))  {
    println("$i -- $j")
}
复制代码

zipTwo parameters are supported, see the output:

image.png

2. useExtension function

Usually read and write from the file output and input stream, you need to call the method to close the output or input stream after the read and write is completed to closeprevent an exception, but the requirement is a requirement, and there is a probability of missing writing during program development.

So kotlin provides an userextension method to help us close the stream, first look at the use:

File("").outputStream().use {
}
复制代码

After use use, there is no need for the program to manually close the stream. Look at the usesource code:

image.png

In the same way, the read-write database cursoralso supports the use use.

3. Sealedsealed class

A sealed class is defined as follows:

sealed class Kit {
    data class H(val name: String = "")
    data class O(val age: Int = 0)
    data class L(val show: Boolean = false)
}
复制代码

In fact, sealed classes are very similar to abstract classes and enumerations, but there are two advantages that are significantly different from abstract classes and enumerations:

  • Class structure hierarchy (compared to abstract classes)

The concrete implementation class of the abstract class can be defined in various locations in the package, which is very inconvenient to manage, while the sealed class has a hierarchical structure, ie 密封类的子类只能和密封类定义在同一个类文件中. Of course, versions after kotlin 1.4 will not be so restrictive

  • Subclass objects support dynamic creation (compared to enumeration)

The safest way to implement a singleton in java is to use an enumeration implementation. The content of each element of the enumeration declaration is fixed, and parameters cannot be passed in externally. and密封类的子类可以声明为object,这个效果就和枚举元素一样,也可以声明为普通的class,可以外部进行传参创建类的对象

Guess you like

Origin juejin.im/post/7087029690250035236