Kotlin 笔记 数据类
2017-01-14 本文已影响20人
yangweigbh
data class User(val name: String, val age: Int)
以下方法会自动生成
-
equals
hashCode()
toString()
-
componentN
函数(用在解构里) -
copy()
--拷贝一个新对象
如果以上任意方法定义在类的body里或者从父类继承了,则不会生成
- primary constructor只要要有一个参数
- primary constructor的参数需要被标为
var
或者val
- 不能是abstract,open,sealed,inner
- 不能继承其他类,但是可以继承接口
因为自动生成了component方法,所以可以使用解构
val jane = User("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age"
kotlin提供Pair
和Triple
这两个data class