Kotlin学习笔记(三十七)数据类

/**
 * 数据类
 * 1.为类加上data关键词之后,该类变成数据类,
 * 会自动为属性添加getter和setter方法,以及copy、toString、hashCode、equals方法,
 * 也有对应的componentN属性,对应的是构造器里面的第N个参数
 * 2.为类重写componentN的方法之后,调用的时候可以使用()符号带参数来表示该对象
 * 3.默认的数据类是final类型的,同时没有无参的构造方法,需加noarg和allopen插件,
 * 就可以生成适当的javaBean
 */
class Country(val id: Int, val name: String) //国家类

@PoKo
data class Country2(val id: Int, val name: String) //国家类2

class ComponentX { //该类重写了component1到component4的方法
    operator fun component1(): String {
        return "斜阳"
    }

    operator fun component2(): String {
        return "空调"
    }

    operator fun component3(): String {
        return "WIFI"
    }

    operator fun component4(): String {
        return "西瓜"
    }
}

fun main(args: Array<String>) {
    val china = Country(0, "中国")
    println(china)
    println(china.id)
    println(china.name)

    val england = Country2(1, "英国")
    println(england)
    println(england.component1()) //component1相当于于第一个参数id
    println(england.component2()) //component2相当于第二个参数name

    //此处的id,name分别对应Country2类中的component1和component2
    val (id, name) = england
    println(id)
    println(name)

    val componentX = ComponentX()
    val (a,b,c,d) = componentX //用()符号加参数承接对象的值
    println("$a $b $c $d")
}
运行结果

此时在字节码生成的Country2类是final类,并且没有无参的构造方法。如果需要当作JavaBean使用,需要添加noarg和allopen插件。步骤如下:

1.新建PoKo.kt文件,声明注解其中代码如下:

annotation class PoKo

2.在build.gradle文件下添加:

apply plugin: 'kotlin-noarg'
apply plugin: 'kotlin-allopen'

noArg {
    annotation("com.kotlin.面向对象.annotations.PoKo")
}

allOpen {
    annotation("com.kotlin.面向对象.annotations.PoKo")
}

3.在build.gradle文件的dependencies中添加如下两行:

classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"

4.在对应的data class数据类添加Poko的注解即可。

@PoKo
data class Country2(val id: Int, val name: String) //国家类2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,990评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,833评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,122评论 6 342
  • 黑龙江项目可行性规划设计 黑龙江可行性研究报告 来源:泓域企划/黑龙江项目可行性规划设计 关键词:黑龙江项目可行性...
    主人host阅读 1,769评论 0 0
  • 很多时候怀念过去,并不是过去过得有多好,只是因为过去的世界太小,容易存有期盼,存有想象,存有不切实际的白日梦。以为...
    相相相柳阅读 1,027评论 0 0

友情链接更多精彩内容