- 1 多申明
fun main(args: Array<String>) {
val pair = Pair(1, "one")
val (num, name) = pair
println("num = $num, name = $name")
}
class Pair<K, V>(val first: K, val second: V) {
operator fun component1(): K {
return first
}
operator fun component2(): V {
return second
}
}
num = 1,name = one
-
2 数据类(data class)
data class User(val name: String, val id: Int)
fun getUser(): User {
return User("Arvin", 1)
}
fun main(args: Array<String>) {
val user = getUser()
println("name = ${user.name}, id = ${user.id}")
// or
val (name, id) = getUser()
println("name = $name, id = $id")
// or
println("name = ${getUser().component1()}, id = ${getUser().component2()}")
println("name = ${getUser().name}, id = ${getUser().id}")
}
> name = Arvin , id = 1
获取key-value值的三种写法
- 3 Map-->HashMap
/kotlin标准库提供Map.Entry组件功能/
fun main(args: Array<String>) {
val map = hashMapOf<String, Int>()
map.put("one", 1)
map.put("two", 2)
map.put("three" ,3)
map.put("three" , 4)
for ((key, value) in map) { //遍历集合里的key-value
println("key = $key, value = $value")
}
}
> 迭代原因就是为了防止存在相同的key值,若发现两个hash值(key)相同时,HashMap的处理方式是用新value替换旧value,这里并没有处理key,这就解释了HashMap中没有两个相同的key。
- 4 自动生成功能(Autogenerated functions)
数据级获取下一个功能,自动生成:
component functions, toString(), equals(), hashCode() and copy().
data class User(val name: String, val id: Int)
fun main(args: Array<String>) {
val user = User("Arvin ", 1)
println(user) // toString() 输出结果为 User(name = Arvin, id = 1)
val secondUser = User("Arvin", 1)
val thirdUser = User("Max", 3)
println(user.equals(secondUser)) //true
println("user == secondUser: ${user == secondUser}") //user == secondUser: true
println("user == thirdUser: ${user == thirdUser}") //user == thirdUser:false
// copy() function
println(user.copy()) //User(name = Arvin, id = 1)
println(user.copy("Max")) //User(name = Max, id = 1)
println(user.copy(id = 2)) //copy后的参数是你想要改成的值
println(user.copy("Max", 2))
println(user.copy().hashcode()) //1969795863
println(user.hashcode()) //1969795863
}
> 注意 equals 与 == 的去别 tostring copy hashcode的用法
.*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★* . .[上一页](http://www.jianshu.com/p/887084b61207) [下一页](http://www.jianshu.com/p/2f84374c6100)..*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★*. .*★* . .*★*. .