定义局部变量
只赋值一次的(只读)局部变量:
val a: Int = 1
val b = 1 // `Int` type is inferred
val c: Int // Type required when no initializer is provided
c = 1 // definite assignment
可变的变量
var x = 5 // `Int` type is inferred
x += 1
属性和字段
定义属性
在Kotlin的类中可以拥有属性。这些可以声明为可变的,使用使用val关键字var关键字或只读。
public class Address {
public var name: String = ...
public var street: String = ...
public var city: String = ...
public var state: String? = ...
public var zip: String = ...
}
使用属性,我们只是将它的name
,就好像它是在Java字段: