属性定义:
var 可变变量
val 只读变量,不可再赋值
class Address {
var name: String = ...
var street: String = ...
var city: String = ...
var state: String? = ...
var zip: String = ...
}
get和set方法
关键字 field,在get和set方法中获取属性值和重新赋值
var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]
实例代码:
var name: String?=""
get() = field
set(value) {
field = value
println("set========================"+value)
}
var age = 0
set(value) {
if (value>0) field = value
}
get or set方法的修饰符
var setterVisibility: String = "abc"
private set // the setter is private and has the default implementation
var setterWithAnnotation: Any? = null
@Inject set // annotate the setter with Inject
Backing Properties
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null) {
_table = HashMap() // Type parameters are inferred
}
return _table ?: throw AssertionError("Set to null by another thread")
}
常量:
const关键字
要求:
1,Top-level or member of an object
2,Initialized with a value of type String or a primitive type
3,No custom getter
const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"
class Constant{
fun method() {
println("-----------constant-----------")
}
}
使用的时候:
导包:import com.heaven.kotlin.demo.entity.SUBSYSTEM_DEPRECATED
println(SUBSYSTEM_DEPRECATED)
Interfaces 接口
interface 关键字。跟java区别不大
kotlin接口中的方法是可以有实现体的
interface MyInterface {
fun bar()
fun foo() {
// optional body
}
}
接口中的属性
interface MyInterface {
val prop: Int // abstract
val propertyWithImplementation: String
get() = "foo"
fun foo() {
print(prop)
}
}
class Child : MyInterface {
override val prop: Int = 29
}
Visibility Modifiers 修饰符
private, protected, internal and public。默认是public
internal:在整个module都是可用的
Data Classes 数据类
只是存储数据和取值使用
关键字:data
data class User(val name: String, val age: Int)
数据类自动生成如下方法
equals()/hashCode()
toString()方法
componentN()方法 对应属性的顺序
copy()方法
要求:
主构造函数至少有一个参数
主构造函数中的所有参数必须被标记为val或者var
数据类不能有以下修饰符:abstract,inner,open,sealed
data class只能实现接口(Kotlin1.1以前的规则),现在也可以继承其它类
copy赋值:
copy方法是编译器自动生成的
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
以Cinema类举例:
data class Cinema(var id:Int,var cinema_name:String) {
}
var cinema = Cinema(1,"四川太平洋")
var cinema2 = cinema.copy(cinema_name = "百老汇")
println(cinema2.component1()) // id值
println(cinema2.component2())// cinema_name 值
println(cinema2) // toString方法:Cinema(id=1, cinema_name=百老汇)