我有以下Kotlin代码:
fun handleResult(clazz: Any){
val store = App.getBoxStore();
if(clazz is List<*> && clazz.size > 0){
val items: List<*> = clazz;
val item = items.get(0);
val box = store.boxFor(item!!::class.java)
box.put(items)
}
}
它需要一个对象,检查它是否是一个集合,如果它是一个集合,则需要一个项目来检查集合项目的类,从名为ObjectBox的库(它是一个数据库)中创建一个Box,然后将它们的项目列表放入数据库。
但是,我在Box.put语句中收到以下错误:
Error:(45, 17) None of the following functions can be called with the
arguments supplied:
public open fun put(@Nullable vararg p0: Nothing!): Unit defined in
io.objectbox.Box
public open fun put(@Nullable p0: (Nothing..Collection<Nothing!>?)):
Unit defined in io.objectbox.Box
public open fun put(p0: Nothing!): Long defined in io.objectbox.Box
我要使用的方法的签名是:
public void put(@Nullable Collection<T> entities)
它接收通用类型的Collection,因为列表是一个Collection,它应该可以工作。
我也已明确将其强制转换为列表,但它仍然表示相同的内容。
谢谢!
最佳答案
问题在于通用的Collection声明需要一个实际的类型。但是,您使用的List <*>没有指定的类型,并且编译器假定与Box关联的通用类型为“Nothing”。
有两种方法可以解决此问题。
if(clazz is List<*> && clazz.size > 0){
val items = clazz
val item = items.get(0)
when (item) {
is Int -> {
val box = store.boxFor(Int::class.java)
box.put(items.filterIsInstance<Int>())
}
is ...
}
}
if(clazz is List<*> && clazz.size > 0){
val items = clazz
val item = items.get(0)
val box = store.boxFor(Int::class.java)
val putMethod = box::class.java.getDeclaredMethod("put", item!!::class.java)
putMethod.invoke(box, items)
}
关于kotlin - 智能转换无法按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188634/