Talking about the development of the advantages of Kotlin

       Overall, Kotlin development has the following advantages:

  • Character Template

  • Space Security

  • Lazy loading

  • Easy-to-read cycle

  • Powerful and easy to use iterators

  • The default parameters

  • DataClass

  • Short and powerful standard library

  • Take-all when (binding sealed class makes the code more comfortable)

  • Spread

  • Simple Bundle quick Parcelable

(A) Character Template

       Development will inevitably need to splice a string based on multiple fields for display, when too long or too complex data logic in Java are too lengthy to implement. Kotlin use $ variable name on the front to express a string of variables and expressions, which simplifies this process.

val str = "hello"
// str length : 5
print("$str length: {$str.length}")

(B) air safety        

       In the process of using Java to develop Android, the security can not avoid a large number of empty judgment code, Kotlin design a whole new type of system to improve the optimization problem. All types are classified into empty and non-empty types, and for a non-empty type mandatory initialization at the outset developers high standard, the use of rigorous variable, is a regulatory requirement. But nullable types may be more widely applied in the program for this, Kotlin have Elvis operators to secure access or to avoid null situation.

// 不可空类型(使用前必须初始化)
var notCanNullInt: Int = 0
// 可空类型
var canNullInt: Int? = null
// 安全访问
print("${canNullInt?.toShort()}")
// 避免空值 为空给与一个默认值
val age = canNullInt ?: 18
// 为空返回
val time = canNullInt ?: return

(C) delay loading

       This can not be said that the empty type of further optimization, development there are always some variables will be initialized in some opportunity, but time is not on the class loader to load. Lazy loading is a good thing, can save the cost of initialization, was initialized when the variable is really needed.

val userInfo: UserInfo by lazy { UserInfo() }
lateinit var person: InvationPerson

(D) easy-to-read cycle

        Kotlin concept of range, this concept allows to create loops more readable and convenient.

// print :0 1 2 3 4 5 6 7 8 9 10
for (i in 0..10) {
    print("$i ")
}
// print :10 9 8 7 6 5 4 3 2 1 0
for (i in 10 downTo 0) {
    print("$i ")
}
// print :0 2 4 6 8 10
for (i in 0..10 step 2) {
    print("$i ")
}
// print :0 1 2 3 4 5 6 7 8 9
for (i in 0 until 10) {
    print("$i ")
}
val map = mapOf("a" to 1, "b" to 2)
// print :a - 1 b - 2
for ((key, value) in map) {
    print("$key - $value")
}

(E) a powerful and easy to use iterators

       For some slightly more complex processing logic to traverse point, Java is not friendly to implement, although there are RxJava remedy, but Kotlin do seem to be a little bit better.

val list = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)

list.forEach { print(it) }
// 映射
val listUp = list.map { it + 2 }
// 过滤
val listFilter = list.filter { it % 2 == 0 }
// asSequence 懒处理 map filter中都存在遍历操作 asSequence可以将它们合并起来 只存在一次遍历 提升性能
val listMore = list.asSequence().map { it + 2 }.filter { it % 2 == 0 }.toList()

(Vi) the default parameters

       Overload is relatively common operation, but sometimes this way there will be many of the same template code. Kotlin default parameters, you can specify a default value to the parameter, and when calling as an assignment to the variable assignment rather like Java have to pass in order to give the value of the parameter. And reasons with default values, so when the call can pass parameters depending on the circumstances, more flexible, more readable and concise.

class Point(val x: Float = 0F, val y: Float = 0F)

val x = Point(x = 10F)// x 10 y 0
val y = Point(y = 10F)// x 0 y 10
val xy = Point(x = 10F, y = 10F)// x10 y10

(Vii) DataClass

       Bean development files is essential, but most of the Java Bean file template code, although there are plug-ins automatically generated, but still will feel more cumbersome, Kotlin these classes can be declared as Data classes will default implementation equals (), hashCode (), toString () and copy () method, from a few dozen lines of Java code to simple few lines of code, Kotlin only declare a data class.

data class Person(
    val name: String,
    val age: Int,
    val sex: Int
){
    //....
}

(Viii) a brief powerful standard library

      This is provided by the library Kotlin, will simplify a lot of boilerplate code after use. Not the same place a little of this and it is their respective points are not the same, and the return is not worth the same as using the product obtained according to the specific circumstances to time on it.

run

val str = "a"
val res = str.run{
    // this指向 "a" 
    // it没有指向
    // 可以直接访问对象得属性
    print(length)
    1 // 最后一行返回值为1
}

let

val str = "a"
val res = str.let{
    // this指向当前class
    // it指向a
    print(it.length)
    "let" // 返回值"let"
}

with

val res = with(user){
    // this 指向user 
    // it无指向
    println(age)
    println(name)
    "with" // 返回值
}

apply

val str = "a"
val res = a.apply{
    // this指向a
    // it无指向
    2 // 返回值
}

(Ix) take-all when

      For Java's switch familiar, but it uses up, there are more restrictions, sometimes face complex logic would seem weak. Kotlin when the expression can match almost anything (literal, enumeration, numbers, range, types, expressions, and even function.

fun whenTest(number: Number?): String {
    return when (number) {
        null, 0 -> "empty"
        1 -> "tiny"
        in 2..5 -> "small"
        is Long -> "big number"
        else -> "unKnow"
    }
}

        In addition, binding Koltin sealed class to handle, such as the receipt of network conditions, error handling, Android adaptation of the multi-processing in the ViewHolder RecyclerView.

// 密封类的存在让整个过程中可能出现的情况更加严谨
sealed class NetWorkResult
data class Success(val resJson: String) : NetWorkResult()
data class Failure(val error: Error) : NetWorkResult()
// 代码更加易读
fun netWorkTest(result: NetWorkResult) {
    when (result) {
        is Success -> {
            showResult(result.resJson)
        }
        is Failure -> {
            showError(result.error)
        }
    }
}

(X) Extended

       Extensions may be a popular feature because it allows you to write less a lot of tools, and make the code more readable look, more concise. For example, make a duplicate to prevent the operation of clicks.

// 扩展点击事件属性(重复点击时长)
var <T : View> T.lastClickTime: Long
    set(value) = setTag(1766613352, value)
    get() = getTag(1766613352) as? Long ?: 0
// 重复点击事件绑定    
inline fun <T : View> T.singleClick(time: Long = 800, crossinline block: (T) -> Unit) {
    setOnClickListener {
        val currentTimeMillis = System.currentTimeMillis()
        if (currentTimeMillis - lastClickTime > time || this is Checkable) {
            lastClickTime = currentTimeMillis
            block(this)
        }
    }
}

(K) simple Bundle quick Parcelable

        And create a map with the same elegant Bundle Kotlin create change, and no longer as an interface in order to achieve Parcelable to write a lot of tedious code like Java.

// 创建Bundle 和创建map 一样优雅
val bundle = bundleOf(
    "KEY_ONE" to 1,
    "KEY_TWO" to 2L,
    "KEY_THREE" to true 
)
// 再也不用写繁琐的Parcelable实现
@Parcelize
data class Person(val name:String):Parcelable

 

Reference: https://juejin.im/post/5db7a7fd51882543c9395254

发布了35 篇原创文章 · 获赞 37 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_34519487/article/details/103885269