Methods
- Kotlin course
- Beginner
- Lesson 109/116
- 5 min
Learn to define methods in a class.
Methods: behaviour of a class
A method is a function defined inside a class. It is called on an instance and can access the properties.
class Person(val name: String) {
fun greet() = "Hello $name"
}
val p = Person("Alex")
println(p.greet()) // Hello AlexA method is behaviour attached to an instance; $name uses the property directly. The call p.greet() runs the method and returns the result. This keeps data and behaviour in one place.
Calling a method
You call a method on an instance with a dot. The method can access the instance's properties directly.
val p = Person("Alex")
val message = p.greet()
println(message)p.greet() runs the method and returns a value. You can assign the result to a variable or print it directly. The parentheses mark the method call.
Practice Add a greet method to Person
Define class Person(val name: String); in its body write fun greet() = "Hello $name". In main create val p = Person("Alex") and print p.greet() with println.
Starter code
fun main() {
// Define a Person class with a greet method
// Create an instance and print the greet call
}Sample solution
class Person(val name: String) {
fun greet() = "Hello $name"
}
fun main() {
val p = Person("Alex")
println(p.greet())
}Expected output
Merhaba Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a fun inside a class called?
- A function outside the class
- A property
- A constant
- A function defined inside the class Correct answer
Explanation: A function inside a class is a method.
2 Match concept to role
| Term | Meaning |
|---|---|
fun greet() |
Method |
val name |
Property |
class Person |
Class |
Person("Alex") |
Instance |
3 Fill in the blank: call the method
val p = Person("Alex")
val message = p.____()
val p = Person("Alex")
val message = p.greet()
Explanation: p.greet() calls the method.