0

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

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • You can treat the receiver (`MockKMatcherScope` here) as the `this` in the function body. The documentation [here](https://kotlinlang.org/docs/lambdas.html#function-literals-with-receiver) can hopefully clarify it. – mkobit Jul 20 '23 at 16:58
  • @mkobit I played with my idea and now I think that it is just an extension. Is it correct ? – gstackoverflow Jul 20 '23 at 17:09
  • It is related to extensions, yes. The concept is the same - function receives an argument which is represented inside the function as `this`. – broot Jul 20 '23 at 17:31

0 Answers0