Methods & Constructors
Methods are a special kind of function that are defined inside a class. They are used to define the behavior of an
object. In Kotlin, methods are defined using the fun
keyword followed by the method name. The method can take
parameters and return a value. Here is an example of a method that takes two parameters and returns the sum of the two
numbers:
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
}
fun main() {
val calculator = Calculator()
val sum = calculator.add(5, 10)
println(sum) // Output: 15
}
In this example, we define a class called Calculator
with a method called add
. The add
method takes two parameters
a
and b
of type Int
and returns the sum of the two numbers. We then create an instance of the Calculator
class
and call the add
method with the values 5
and 10
. The result is stored in the sum
variable and printed to the
console.
Constructors
Constructors are special methods that are called when an object is created. They are used to initialize the object with
default values or values passed as arguments. In Kotlin, the primary constructor is defined in the class header, and
code is ran using them in the init
block. Here is an example of a class with a primary constructor:
class Person(name: String, age: Int) {
init {
println("Name: $name")
println("Age: $age")
}
}
But now we have a problem. We can't access the name
and age
properties outside of the init
block. To fix this, we
can define properties in the class header and initialize them using the primary constructor, the same way you can
declare normal properties:
class Person(val name: String, val age: Int) {
init {
println("Name: $name")
println("Age: $age")
}
}
So now we can access the name
and age
properties outside of the init
block. Here is an example of creating a
Person
object with a name and age:
fun main() {
val person = Person("Alice", 30) // Output: Name: Alice
// Age: 30
println(person.name) // Output: Alice
println(person.age) // Output: 30
}
In this example, we create a Person
object with the name "Alice" and age 30
. We then print the name
and age
properties of the person
object using the println
function.
Secondary Constructors
In addition to the primary constructor, you can define secondary constructors in a class. Secondary constructors are
defined using the constructor
keyword and can have different parameter lists than the primary constructor. Here is an
example of a class with a secondary constructor:
class Person {
var name: String = ""
var age: Int = 0
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
In this example, we define a class called Person
with two properties name
and age
. We then define a secondary
constructor that takes a name
and age
parameter and assigns them to the properties. This also uses the this
keyword which is used to refer to the current object from within itself, as you can not declare properties within the
parameters of a secondary constructor.