简体   繁体   中英

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?

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)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM