1、定义类与field关键字,以及计算属性,和防范竞态条件
class Student { //field关键字:Kotlin针对你定义的每个属性,都会产生一个field,一个getter,以及一个setter //field用来存储属性数据,不能直接定义field,kotlin会封装field,保护它里面的数据,只暴露给 //getter和setter方法使用。 var name: String = "jack" get() = field.capitalize() set(value) { field = value.trim() } //计算属性 //计算属性是通过一个覆盖的get或set运算符来定义,这时field就不需要了 val rolledValue get() = (1..9).shuffled().first() //1~9之间的随机数,取第一个 //防范竞态条件 var words: String? = "hello" fun saySomething() { words?.also { println("Hello ${it.toUpperCase()}") }.also { println("Hi $it") } } } fun main() { var p = Student() println(p.name) p.name = " rose " println(p.name) println(p.rolledValue) p.saySomething() }
输出结果
Jack Rose 9 Hello HELLO Hi hello
2、主构造函数
/** * 主构造函数:我们在Player类的定义头中定义一个主构造函数,使用临时变量为Player的各个属性提供初始值 * 在Kotlin中,为便于识别临时变量(包括仅引用一次的参数),通常都会以下划线开头的名字命名 */ class Player( _name: String, _age: Int, _isNormal: Boolean ) { var name = _name get() = field.capitalize() set(value) { field = value.trim() } var age = _age get() = field.absoluteValue set(value) { field = value.absoluteValue } var isNormal = _isNormal } fun main() { var player = Player("Jack", 30, true) player.name = "tool" println("${player.name}, ${player.age}, ${player.isNormal}") }
输出结果如下
Tool, 30, true
3、次构造函数
/** * 在主构造函数里定义属性 * Kotlin允许你不使用临时变量赋值,而是直接用一个同时指定参数和类属性 * 通常,我们更喜欢用这种方式定义类属性,因为它会减少重复代码 */ class Player2( _name: String, var age: Int, var isNormal: Boolean ) { var name = _name get() = field.capitalize() set(value) { field = value.trim() } //次构造函数 //我们可以定义多个次构造函数来配置不同的参数组合 constructor(name: String) : this(name, age = 100, isNormal = false) constructor(name: String, age: Int) : this(name, age = 100, isNormal = false) { this.name = name.toUpperCase() } } fun main() { val player = Player2("Jack", 30, true) player.name = "tool" println("${player.name}, ${player.age}, ${player.isNormal}") val player2 = Player2("Rose") println(player2.name) var player21 = Player2("Jacky", 30) println("${player21.name},${player21.age}") }
输出结果如下
Tool, 30, true Rose JACKY,100
4、多个次构造函数来配置不同的参数组合
class Player3( _name: String, var age: Int = 20, var isNormal: Boolean ) { var name = _name get() = field.capitalize() set(value) { field = value.trim() } //次构造函数 //我们可以定义多个次构造函数来配置不同的参数组合 constructor(name: String) : this(name, age = 100, isNormal = false) constructor(name: String, age: Int) : this(name, age = 100, isNormal = false) { this.name = name.toUpperCase() } } fun main() { var player = Player3(isNormal = false, _name = "Jack") println("${player.name}, ${player.age}, ${player.isNormal}") }
输出结果如下
Jack, 20, false