- Kotlin Programming By Example
- Iyanu Adelekan
- 128字
- 2025-04-04 17:16:16
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.