Kotlin数据类

一、数据类
再见,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'
}

三、来看一个例子

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")
}

输出结果:

Country(id=0, name=中国)
0
中国
0
中国
您好,我是 1 1 0

好了,结束了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值