Kotlin数据类

简介: 一、数据类 再见,Javabean 默认实现了copy、toString等方法 componentN方法二、allOpen和noArg插件 build.

一、数据类
再见,Javabean
默认实现了copy、toString等方法
componentN方法

二、allOpen和noArg插件
这里写图片描述

build.gradle的源码

group 'net.println.kotlin'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}

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

noArg{
    annotation("net.println.kotlin.chapter4.annotations.PoKo")
}

allOpen{
    annotation("net.println.kotlin.chapter4.annotations.PoKo")
}

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.11'
}
AI 代码解读

三、来看一个例子

package net.println.kotlin.chapter4.dataclass

import net.println.kotlin.chapter4.annotations.PoKo

/**
 * @author:wangdong
 * @description:
 */
/**加data后就不用再写toString方法了*/
@PoKo
data class Country(val id: Int,val name: String)


/**
 * 自定义一个
 */
class ComponentX{
    operator fun component1(): String{
        return "您好,我是"
    }

    operator fun component2(): Int{
        return 1
    }

    operator fun component3(): Int{
        return 1
    }

    operator fun component4(): Int{
        return 0
    }
}

fun main(args: Array<String>) {
    val china = Country(0,"中国")
    println(china)
    //写法一,component1是默认有的
    //component1对应第一个参数
    println(china.component1())
    //component2对应第二个参数
    println(china.component2())

    //写法二
    //下面类似
    val (id,name) = china
    println(id)
    println(name)

    //写法三
    for ((index,value) in args.withIndex()){
        println(index)
        println(value)
    }

    val componentX = ComponentX()
    val (a,b,c,d) = componentX
    println("$a $b $c $d")
}
AI 代码解读

输出结果:

Country(id=0, name=中国)
0
中国
0
中国
您好,我是 1 1 0
AI 代码解读

好了,结束了

目录
打赏
0
0
0
0
13
分享
相关文章
|
7月前
|
Kotlin教程笔记(20) - 枚举与密封类
Kotlin教程笔记(20) - 枚举与密封类
83 8
|
7月前
|
Kotlin教程笔记(13) - 类及成员的可见性
Kotlin教程笔记(13) - 类及成员的可见性
96 3
Kotlin教程笔记(2) - 类与构造器
Kotlin教程笔记(2) - 类与构造器
60 1
​ Kotlin教程笔记(13) - 类及成员的可见性
​ Kotlin教程笔记(13) - 类及成员的可见性
Kotlin - 类及成员的可见性
Kotlin - 类及成员的可见性
Kotlin - 数据类
Kotlin - 数据类
67 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问