Class Basics
In this page:
class ClassName {
fun method() { }
}
class ClassName(val property: Type, var other: Type)
val instance = ClassName(value1, value2)
Declaring a Simple Class
A class groups related data and behavior under one name, defined with the class keyword. Even a class with no properties or methods can be declared and instantiated.
Example: Declaring a Simple Class
// Define a class `Greeter`
class Greeter {
// Define the function `greet` with no parameters
fun greet() {
// Print "Hello from Greeter!" to the console, with a trailing newline
println("Hello from Greeter!")
}
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `greeter`, set to `Greeter()`
val greeter = Greeter()
greeter.greet()
}
Login to try C/C++/Java/PHP code in the editor
Properties in the Primary Constructor
Declaring parameters with val or var directly in the class's parentheses creates properties automatically, avoiding the need to write separate field declarations and assignments.
Example: Properties in the Primary Constructor
// Define a class `Dog`
class Dog(val name: String, val breed: String)
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `dog`, set to `Dog("Rex", "Labrador")`
val dog = Dog("Rex", "Labrador")
// Print "${dog.name} is a ${dog.breed}" to the console, with a trailing newline
println("${dog.name} is a ${dog.breed}")
}
Login to try C/C++/Java/PHP code in the editor
Creating Instances
An instance of a class is created by calling its name like a function, passing arguments that match its primary constructor's parameters.
new keyword is needed in Kotlin, unlike Java.Example: Creating Instances
// Define a class `Point`
class Point(val x: Int, val y: Int)
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `p1`, set to `Point(1, 2)`
val p1 = Point(1, 2)
// Declare a read-only variable `p2`, set to `Point(3, 4)`
val p2 = Point(3, 4)
// Print "p1=(${p1.x}, ${p1.y}), p2=(${p2.x}, ${p2.y})" to the console, with a trailing newline
println("p1=(${p1.x}, ${p1.y}), p2=(${p2.x}, ${p2.y})")
}
Login to try C/C++/Java/PHP code in the editor
Member Functions
Functions declared inside a class body are member functions (methods) that operate on that instance's own properties, accessible via this implicitly.
Example: Member Functions
// Define a class `Circle`
class Circle(val radius: Double) {
// Define the function `area` with no parameters and returning a Double
fun area(): Double = Math.PI * radius * radius
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `circle`, set to `Circle(3.0)`
val circle = Circle(3.0)
// Print "Area: ${circle.area()}" to the console, with a trailing newline
println("Area: ${circle.area()}")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
classkeyword needs a following pair of parentheses()for a primary constructor even when it has parameters, or omitting them entirely if there are none. - Not realizing that properties declared in the primary constructor with
val/varautomatically become accessible class members. - Creating an object but forgetting the
()when calling the constructor, e.g. writingDoginstead ofDog().
- A class is declared with the
classkeyword followed by a name and, optionally, a primary constructor. - Properties declared with
val/varinside the constructor parentheses become class members automatically. - An object of a class is created by calling its constructor like a function:
ClassName(...). - Kotlin classes are
final(cannot be subclassed) by default unless markedopen.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: