Working with classes

A class is declared using the class keyword followed by the class name:

class Person

As in the preceding example, a class in Kotlin need not have a body. Though this is charming, almost all the time you will want your class to have characteristics and behaviors placed within a body. This can be done with the use of opening and closing brackets:

class HelloPrinter {  fun printHello() {    println("Hello!")  }}

In the preceding code snippet, we have a class named HelloPrinter with a single function declared in it. A function that is declared within a class is called a method. Methods can also be referred to as behaviors. Once a method is declared, it can be used by all instances of the class.

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.