19

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 Answer 1

19

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>()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.