Kotlin Programming By Example
上QQ阅读APP看书,第一时间看更新

Properties

Classes can have properties that may be declared using the var and val keywords. For example, in the following code snippet, the Person class has three properties, age, firstName, and surname:

class Person {  var age = 0
var firstName = ""
var surname = ""
}

Properties can be accessed through an instance of the class holding the property. This is done by appending a single dot character (.) to an instance identifier followed by the property name. For example, in the following code snippet, an instance—named person—of the Person class is created and its firstName, surname, and age properties are assigned by accessing the properties:

val person = Person()
person.firstName = "Raven"
person.surname = "Spacey"
person.age = 35