darkgrin
darkgrin

Reputation: 580

Is it expected that I can call a function with a receiver object by passing the receiver object in as the first argument?

Using the example in Kotlin's document on Function Literals with Receiver:

val sum = fun Int.(other: Int): Int = this + other

The sum function can be invoked like this as if it were a method of the receiver object:

1.sum(2)

However I noticed that we can also invoke the function like this:

sum(1, 2)

Of course both of them give the same results. My question is if the behavior is expected? Or did I miss something in the documentation?

Upvotes: 0

Views: 85

Answers (1)

nhaarman
nhaarman

Reputation: 100398

Yes, extension functions are compiled as static functions with the receiver as the first parameter. So for example:

 fun Int.sum(other: Int): Int = this + other

somewhat compiles to:

 static int sum(int receiver, int other) {
   return receiver + other;
 }

Upvotes: 2

Related Questions