一、数据类
再见,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
好了,结束了