Difference between someFunction() and val x : Int get() = someFunction()

The title says it , I couldn’t understand the real difference in the effect of those two

val x : Any get() = someFunction()
//or 
someFunction()

Do they have any difference memory wise , performance wise , and other perspectives ?

Not sure what exactly you’re asking about; the two statements are entirely different. The first one declares a property with a getter that invokes a function. The other one is simply a function call.

Yes I know what by definition they are different , by I mean which is more efficient and what are the use cases for each

Sorry, I don’t understand how it’s possible to compare the efficiency of declaring a property and calling a function. Declaring a property does not execute any code at all; it just creates a property that you can access later. Calling a function executes that function.

1 Like

So what difference does it make if I need let’s say an instance of a class to make it as a function or an immutable variable with a getter

class Instance {
    companion object {
        fun getInstance() = Instance()
        val INSTANCE : Instance get() = Instance()
    }
}

In this case the only difference is the syntax you will use to access the value from Kotlin code. The getter of a property will be compiled to a method which will be identical to the getInstance() method you’ve declared.

Ahh i see, it got me a bit confused between being “immutable” and of variable value … it seems a bit confusing , I thought the whole purpose of immutability is to make the thing non-changing or independent

A val property is not necessarily immutable. The only thing val means is that the value of the property can’t be changed through the external API of the class.

1 Like

What you may be thinking about is a value without a getter that does not call the function but keeps the value.

class Instance {
   companion object {
     val INSTANCE = Instance()
   }
}

Or, although through the vaguaries of jvm classloaders not needed:

class Instance {
   companion object {
     val INSTANCE by lazy { Instance() }
   }
}

No the thing was some confusion between immutability, val , and val with a getter , i thought that val was supposed to be immutable and still it can have a changed value.

Yole cleared it out clearly. Thanks !