Home > Software engineering >  Specify method paramater class type in 'every' block
Specify method paramater class type in 'every' block

Time:09-30

I have a problem when using any() statement inside save() method (Spring Framework). I get error:

Type inference failed: Not enough information to infer parameter T in inline fun any( ): T
Please specify it explicitly.

Is there anyway to pass method parameter so I wouldn't have error? I tried to pass object as a parameter but save() method creates new object which requires to use any().

every { repository.save(any()) } returns classObject

error when pass object:

io.mockk.MockKException: no answer found for: Repository(#10).save(app.core.model.Class@734a4045)

CodePudding user response:

You can give the function a type parameter by doing any<Type>().

Example:

fun <T> any(defaultValue: T? = null): T? = defaultValue


fun main() {
    val s = any<String>()
    println(s)
    val i = any<Int>()
    println(i)
    val j = any(10) // type inferred from arg
    println(j)
    val k: Int? = any() // type inferred from variable
    println(k)
}

Prints:

null
null
10
null

The reason the type cannot be inferred is that in your case, save() probably accepts values of type Any so the compiler cannot infer any specific type.

Incidentally, if you need access to T inside a generic function, Kotlin allows you to make the function reified.

  • Related