Kotlin and mockito: Type mismatch when using vararg on the begin of the function

Viewed 577

Given a class such as the "Target" class below:

class Target {

fun <R> target(vararg filter: String, mapper: (String) -> R): R {
    println(filter.contentDeepToString())
    return mapper("target")
}

}

And a test such as below:

@Test
fun test() {
    val mockTarget = mock(Target::class.java)
    Mockito.`when`(mockTarget.target<Int>("Hello World", any<(String) -> Int>()))
           .thenReturn(1)
}

I'm getting the Type mismatch: inferred type is ((String) -> Int)! but String was expected.

I know the vararg usually goes to the end of the function, in fact if you move the vararg to the end it compiles.

Once mockito looks to the bytecode, I'm wondering if it is possible to use mockito in such odd method.

Edit

The code runs as expected, the problem happens only when you try to mock.

fun main(args: Array<String>) {
    val result = Target().target("Hello World") {
        123
    }
    println("$result == 123? ${result == 123}")
}
// out:
// [Hello World]
// 123 == 123? true
1 Answers

Use named argument. Add mapper = before your lambda, like this:

@Test
fun test() {
    val mockTarget = Mockito.mock(Target::class.java)
    Mockito.`when`(
        mockTarget.target<Int>(
            "Hello World",
            mapper = Mockito.any<(String) -> Int>()
        )
   ).thenReturn(1)
}
Related