difference between invoke and init kotlin
Asked Answered
P

1

8

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?

Provo answered 14/7, 2021 at 8:2 Comment(3)
I don't understand your point "everything we do in invoke method, it can be done in init constructor". invoke is a method (which happens to be also an operator), and init is an initializing block - they have nothing in common. I assume your problem is the lack of investing into reading the docs and trying out the codeCatnap
@Catnap I don't know what you got from my question, but I wasn't asking about the structure. I asked what is the usage of each.Provo
invoke can be used on lambdas especially on nullable lambdas to call the body with the required arguments while init is a block that is called after constructor call of a class to create an object to initialize some property or to do other stuff. No idea why you are confused about them.Estis
R
7

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
Radiosonde answered 14/7, 2021 at 9:41 Comment(1)
thank you for your answer. tbh it wasn't only me, I saw multiple student asking my question without getting any answers. I was confused because I thought the result will appear whenever it is instantiated but now I got it completely. thank you so much.Provo

© 2022 - 2024 — McMap. All rights reserved.