'Is it possible to overload function with receiver operator in Kotlin?

I can define invoke inside a class

class A {
   fun invoke(x: Double): Double {
       ...
   }
}

and then use class instance as a functiion

val a: A()
val b = a(2.3)

right?

But can I define class instance to simulate function with receiver?

val o: MyClass()
val a: A()
val b = o.a(2.3)

Is it possible?



Solution 1:[1]

and then use class instance as a functiion

The invoke operator is just a way to define what happens when using the syntax () on some instance. Just like you can overload what + means, you can overload what () means. It's not exactly making an instance of A "usable as a function", but rather defining the operator () on instances of A. This is why I think it cannot really translate to "making it usable as a function with receiver".

The obvious easy way to declare an extension function would be the following:

fun MyClass.a(input: Double): Double = TODO(...)

But this doesn't seem to suit your needs. If what you really want is to add such functions as "capabilities" to some instances dynamically "on the spot" as in your example, I guess you could do so by defining such extension in a class that you provide as scope:

class A {
   fun MyClass.a(x: Double): Double {
       ...
   }
}

fun main() {
    val o = MyClass()
    
    val b = with(A()) { // brings this instance of A in scope to add the extension
        o.a(2.3)
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joffrey