I'm studying about operator overloading in kotlin and I ran into invoke
method. When I did my research about it I found out it works much similar to init
constructor of every class.
I cannot get my head around the difference and they seem to be alike because everything we do in invoke
method, it can be done in init
constructor as well.
so what is the difference and when should we use each?
This is not a good comparison. The init
block is run every time the class is instantiated, with any kind of constructor as we shall see next. But the invoke
method can be called multiple times, just like any other method of the class.
Suppose you want to return all the values of a class as string in different parts of the code. You can implement it in invoke and call it wherever necessary without naming the function.
example:
class Person(val name :String,var age:Int) {
fun incrementAge(){
age =age + 1
}
operator fun invoke():String {
return "name: $name \nage: $age\n"
}
}
fun main() {
val x = Person("lionel",35)
println(x())
x.incrementAge()
println(x())
}
Output:
name: lionel
age: 35
name: lionel
age: 36