Kotlin的一些使用技巧

一、Map的plus操作符

使用+ - 對map進行操作

    /**
     * map的plus操作符
     * 使用+ - 對map進行操作
     */
    @Test
    fun plus () {
        val map = mapOf("one" to 1,"two" to 2,"three" to 3)
        println("原始數據${map}")
        // plus (+) map的加號操作符
        println(map+Pair("four",4))
        println(map+Pair("one",10))
        println(map+Pair("one",20)+Pair("five",5))
        // minus (-) 減法操作符
        println(map-"one")
        println(map- listOf("two","three","one"))

    }

原始數據{one=1, two=2, three=3}
{one=1, two=2, three=3, four=4}
{one=10, two=2, three=3}
{one=20, two=2, three=3, five=5}
{two=2, three=3}
{}

二、Map 集合的默認值-withDefault

當map中的key不存在的時候返回默認值

   /**
     * 當map中的key不存在的時候返回默認值
     */
    @Test
    fun withDefault() {
        val map = mapOf("java" to 1, "kotlin" to 2, "python" to 3).withDefault { 0 }
        println(map.getValue("java")) // 1
        println(map.getValue("kotlin")) // 2
        println(map.getValue("python")) // 2
        println(map.getValue("c++")) // 0 默認值

    }
1
2
3
0

當我們使用plus操作符重新對map相加,返回新的map的時候,會去除原來map中的默認值,當我們在獲取key不存在的value的時候,就不會返回默認值,拋出異常

   /**
     * 當map中的key不存在的時候返回默認值
     */
    @Test
    fun withDefault() {
        val map = mapOf("java" to 1, "kotlin" to 2, "python" to 3).withDefault { 0 }
        val newMap = map+Pair("c",4)
        println(newMap.getValue("c++"))

    }
java.util.NoSuchElementException: Key c++ is missing in the map.

三、使用 require 或者 check 函數作爲條件檢查

   @Test
    fun requireAndCheck() {
        //傳統做法
        val age = -1;
        if (age < 0) {
            throw IllegalArgumentException("age must be >0")
        }
        //使用require檢查
        require(age > 0) {
            throw  IllegalArgumentException("age must be >0")
        }
        //使用checkNotNull做檢查
        val name: String? = null
        checkNotNull(name) {
            "name must be not null"
        }
    }

四、in 和 when 關鍵字

使用in when關鍵字 替換contains

    /**
     * 使用in when關鍵字 替換contains
     */
    @Test
    fun inAndWhen() {
        val input = "kotlin"
        val list = listOf("java", "kotlin")
        val set = setOf("c", "c++", "python")
        when (input) {
            in list-> println("in list")
            in set-> println("in set")
            else-> println("no input in")

        }

    }
in list

五、let、with、run、apply、also

具體每個函數的區別,迷迷糊糊記不清,等開發的時候慢慢體會把,先知道怎麼用。

  @Test
    fun addition_isCorrect() {

        val s = Student()
        s.let {
            it.name = "let"
            it.sex = "let sex"
            println(it.name)
            println(it.sex)
            it


        }

        with(s) {
            name = "with"
            sex = "with sex"
            println(name)
            println(sex)
            name

        }
        s.run {
            name = "run"
            sex = "run sex"
            println(name)
            println(sex)
            name

        }
        s.apply {
            name = "apply"
            sex = "apply sex"
            println(name)
            println(sex)
            name
        }
        s.also {
            it.name = "also"
            it.sex = "also sex"
            println(it.name)
            println(it.sex)
            it
        }


    }
let
let sex
with
with sex
run
run sex
apply
apply sex
also
also sex

六、by lazy用於單例

by lazy 聲明的變量只能用 val,因爲初始化完成之後它的值是不會變的。

package com.haiheng.voiceandbook

class User private constructor() {
    companion object {
        /**
         * 方式一
         */
        val user by lazy { User() }

        /**
         * SYNCHRONIZED
         * 默認的,多個線程訪問,只有一個線程去初始化lazy對象
         *
         *
         * PUBLICATION
         *
         * 如果對象還沒初始化,可以有多個線程去調用,如果初始化完成,其他線程使用初始化完成的值
         *
         *
         * NONE
         * 單線程使用,不會有併發問題
         *
         */
        /**
         * 方式2
         */
        val user1 by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){User}
        /**
         * by lazy 聲明的變量只能用 val,因爲初始化完成之後它的值是不會變的。
         */
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章