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,因为初始化完成之后它的值是不会变的。
         */
    }

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