[英]In Kotlin, how can I instantiate a generic class using a native java parameter?
I am exploring using BDB JE (Berkeley DB Java Edition) with Kotlin. 我正在探索将Kotlin与BDB JE(伯克利DB Java版)结合使用。 Knowledge of BDB is not necessary to answer this question.
不需要BDB知识就可以回答这个问题。
BDB has a method that looks like this: BDB的方法如下所示:
store.getPrimaryIndex(Int::class.java, "Int", Person::class.java, "Person")
I want to do things generically, so I wrote this 我想一般地做事,所以我写了这个
inline fun <reified TModel : Any, reified TKey : Any> getIndex() =
return store.getPrimaryIndex(TKey::class.java, TKey::class.simpleName, TModel::class.java, Model::class.simpleName)
So far so good. 到现在为止还挺好。 I now want to pass this index object to a class, which looks like this:
我现在想将此索引对象传递给一个类,如下所示:
class ModelStore<TModel, TKey>(index : PrimaryIndex<TKey, TModel>) {
private val index = index
fun get(key : TKey): TModel = index.get(key)
fun put(model : TModel) = index.put(model)
}
But if I try and pass the output from getIndex<User, Int>()
to ModelStore<User, Int>
I get the following error: 但是,如果我尝试将
getIndex<User, Int>()
的输出传递给ModelStore<User, Int>
, ModelStore<User, Int>
出现以下错误:
Type inference failed: Expected type mismatch: Inferred type is
PrimaryIndex<TModel!, TKey!>!
类型推断失败:预期类型不匹配:推断类型为
PrimaryIndex<TModel!, TKey!>!
butPrimaryIndex<TModel, TKey>
was expected.但应使用
PrimaryIndex<TModel, TKey>
。
My question: Can I pass the the index to the ModelStore
? 我的问题:我可以将索引传递给
ModelStore
吗? How do I convince the type-system that this is kosher? 我如何说服类型系统这是犹太洁食?
The simplest workaround is to cast the types: 最简单的解决方法是强制转换类型:
ModelStore<User, Int>(getIndex<User, Int>() as PrimaryIndex<User, Int>)
Also I would expect it to work without specifying the types: 我也希望它能在不指定类型的情况下工作:
ModelStore(getIndex<User, Int>())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.