Kotlin中参数化类的类文字语法 [英] Class literal syntax for parameterized classes in Kotlin

查看:84
本文介绍了Kotlin中参数化类的类文字语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Kotlin中模拟一个函数

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

推荐答案

该错误是正确的,并且您提供的解决方案是预期的解决方案.这样做的理由是,由于泛型类型参数在运行时不会得到验证,因此您只能获得表示 class 的对象,而不是表示 type 的对象.

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.

但是有一种解决方法:如果通过一个经过修饰的类型参数使用类文字语法,然后在调用站点将其替换为所需的类型,则将获得相同的KClass对象,但具有实际的参数假如.您可以声明以下函数:

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

并像这样使用它:

val f = mock<(Int, Int) -> Unit>()

这篇关于Kotlin中参数化类的类文字语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆