本文主要讲述数据类,以前用java实现数据类很麻烦,写很多代码,就是搭个数据类的框架。kotlin用data class 关键字,给你简化了数据类的创建,比较贴心。
就是自动为你创建了:equals()、hashCode()、toString()。
其中,equals() 方法用于判断两个数据类是否相等。hashCode()方法作为equals()的配套方法,也需要一起 重写,否则会导致HashMap、HashSet等hash相关的系统类无法正常工作。toString()方法 用于提供更清晰的输入日志,否则一个数据类默认打印出来的就是一行内存地址。
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
println("Hello, world!!!")
val cellphone1=Cellphone("Samsung",1299.99)
val cellphone2=Cellphone("Samsung",1299.99)
println(cellphone1)
println(cellphone2)
println("cellphone1 equal cellphone2?:"+(cellphone1==cellphone2))
}
data class Cellphone(val brand:String,val price:Double){}
运行结果:
Hello, world!!!
Cellphone(brand=Samsung, price=1299.99)
Cellphone(brand=Samsung, price=1299.99)
cellphone1 equal cellphone2?:true
本文介绍了Kotlin中的dataclass特性,如何通过dataclass关键字快速创建数据类,自动生成equals(),hashCode(),toString()方法,对比Java中手动实现的繁琐过程。
886

被折叠的 条评论
为什么被折叠?



