Class literal syntax for parameterized classes in Kotlin

后端 未结 1 1712
面向向阳花
面向向阳花 2020-12-16 13:20

I\'m trying to mock a function in Kotlin

Mockito.mock(Function2::class.java)

and it says \"Only classes are allow

相关标签:
1条回答
  • 2020-12-16 14:06

    The error is correct and the solution you provided is the intended one. The rationale here is that since generic type arguments are not reified at runtime, you can only obtain an object representing a class, not a type.

    There's a workaround though: if you use the class literal syntax through a reified type parameter, substituting it with the desired type at the call site, you'll get the same KClass object but with the actual arguments you've provided. In your case you can declare the following function:

    inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java) as T
    

    And use it like this:

    val f = mock<(Int, Int) -> Unit>()
    
    0 讨论(0)
提交回复
热议问题