What is the puripose of `additional receiver type` in Kotlin lambda declaration?

48 Views Asked by At

I am a java developer but develop Kotlin for two weeks and during test implementation I've found interesting construction :

every {
    mockedObject.foo(arg)
} returns bar

I've checked every finction declaration:

/**
 * Starts a block of stubbing. Part of DSL.
 *
 * Used to define what behaviour is going to be mocked.
 *
 * @sample
 * interface Navigator {
 *   val currentLocation: String
 * }
 *
 * val navigator = mockk<Navigator>()
 * every { navigator.currentLocation } returns "Home"
 *
 * println(navigator.currentLocation) // prints "Home"
 * @see [coEvery] Coroutine version.
 */
fun <T> every(stubBlock: MockKMatcherScope.() -> T): MockKStubScope<T, T> = MockK.useImpl {
    MockKDsl.internalEvery(stubBlock)
}

I've got that it is a function which accepts a single argument named stubBlock

It is a lambda which accepts no arguments but returns T

But I don't understand meaning of MockKMatcherScope here

(stubBlock: MockKMatcherScope.() -> T)

Looks like it is somehow related:

Function types can optionally have an additional receiver type, which is specified before the dot in the notation: the type A.(B) -> C represents functions that can be called on a receiver object A with a parameter B and return a value C. Function literals with receiver are often used along with these types.

But I stil don't understand how to use that additiona receiver type.

UPDATE

My IDE helped me to convert it to:

    val every: MockKStubScope<String, String> = every(
        stubBlock = fun MockKMatcherScope.(): String{
            return mockedObject.foo(arg)
        },
    )
    every.returns(bar)

Looks like it is related to extension functionality in Kotlin

So looks like I pass instance of MockKMatcherScope enriched with 1 functions

0

There are 0 best solutions below