美文网首页Kotlin编程
Kotlin 笔记 数据类

Kotlin 笔记 数据类

作者: yangweigbh | 来源:发表于2017-01-14 19:08 被阅读20次
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提供PairTriple这两个data class

相关文章

网友评论

    本文标题:Kotlin 笔记 数据类

    本文链接:https://www.haomeiwen.com/subject/nfaebttx.html