Kotlin also 交换值

79 阅读2分钟

Int 和 List 使用also 函数是有区别的 aslo 中的it 是val 类型的,

aslo 返回的是it 对象,不是 b

fun main() {
    val numbers = mutableListOf("one", "two", "three")
    println("外部打印在列表添加新元素: $numbers")
    val newNumbers = numbers.also {
        it.add("Five")
        println("also 中在列表添加新元素it: $it")// 在列表添加新元素: [one, two, three, Five]
        println("also 中在列表添加新元素 it hashCode: ${it.hashCode()}")
        println("also 中在列表添加新元素numbers: $numbers")// 在列表添加新元素: [one, two, three, Five]
        println("also 中在列表添加新元素 numbers.hashCode: ${numbers.hashCode()}")
    }
    println("also 之后 外部打印在列表添加新元素   numbers : $numbers")
    println("also 之后 外部打印在列表添加新元素   numbers.hashCode : ${numbers.hashCode()}")
    println("also 之后 外部打印在列表添加新元素newNumbers : $newNumbers")
    println("also 之后 外部打印在列表添加新元素newNumbers.hashCode : ${newNumbers.hashCode()}")
    println()
    
    //交换 a和b 的值
    var a = 1
    var b = 2
    // aslo 返回的是it 对象,不是 b
    a = b.also {
//        it = a // 报错  Val cannot be reassigned
        b = a
        println("also  A= $a, b= $b")// 打印: also  A= 1, b= 1
        println("also  it= $it")//打印:also  it= 2
    }
    println("A= $a, b= $b")//打印:A= 2, b= 1
//sampleEnd
}

打印结果
外部打印在列表添加新元素: [one, two, three]
also 中在列表添加新元素it: [one, two, three, Five]
also 中在列表添加新元素 it hashCode: -1773084773
also 中在列表添加新元素numbers: [one, two, three, Five]
also 中在列表添加新元素 numbers.hashCode: -1773084773
also 之后 外部打印在列表添加新元素   numbers : [one, two, three, Five]
also 之后 外部打印在列表添加新元素   numbers.hashCode : -1773084773
also 之后 外部打印在列表添加新元素newNumbers : [one, two, three, Five]
also 之后 外部打印在列表添加新元素newNumbers.hashCode : -1773084773


also  A= 1, b= 1
also  it= 2
A= 2, b= 1

通过String 来中的hasCode 来证明一下,

var str1 = "1234"
var str2 = "56789"
println("also 前 str1= ${str1.hashCode()}, str2= ${str2.hashCode()}")
str2 = str1.also {
    str1 = str2
    println("str1= $str1, str2= $str2")
    println("str1= ${str1.hashCode()}, str2= ${str2.hashCode()}")
    println("it= ${it}, it.hashCode= ${it.hashCode()}")
    
    //it = "不能被赋值"

}
println("str1= $str1, str2= $str2")

打印结果
also 前 str1= 1509442, str2= 50609975
str1= 56789, str2= 56789
str1= 50609975, str2= 50609975
it= 1234, it.hashCode= 1509442
str1= 56789, str2= 1234