Class literal syntax for parameterized classes in

2020-02-10 03:20发布

问题:

I'm trying to mock a function in Kotlin

Mockito.mock(Function2<Int, Int, Unit>::class.java)

and it says "Only classes are allowed on the left hand side of a class literal". What's the proper way to obtain a reference to a statically known parameterized class? For now I live with an ugly cast

Mockito.mock(Function2::class.java) as (Int, Int) -> Unit

回答1:

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>()


标签: kotlin