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

Get Kotlin Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.