泛型作为构造函数的参数

时间:2019-05-20 18:42:31

标签: generics kotlin

我正在查看一个包含以下条目的代码:

open class PersonFinder: Finder<Long, Person>(Person::class.java)
open class CompanyFinder: Finder<Long, Company>(Company::class.java)
open class DeviceFinder: Finder<Long, Device>(Device::class.java)

我想要一个更通用的方法,像这样:

open class GenericFinder<T>: Finder<Long, T>(T::class.java)

,但是语法无效,因为T :: class.java不能在那里用作参数。有什么办法可以使我以惯用的方式工作吗?

2 个答案:

答案 0 :(得分:0)

我想我找到了解决方法:

open class GenericFinder<T>(type: Class<T>) : Finder<Long, T>(type)

答案 1 :(得分:0)

如果(至少合理地)想要直接使用GenericFinder而不是对其进行子类化,则可以使用reified type parameter添加一个辅助函数:

open class GenericFinder<T>(type: Class<T>) : Finder<Long, T>(type) { ... }

inline fun <reified T> GenericFinder() = GenericFinder(T::class.java)
相关问题