智能投射不能按预期工作

我有以下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 statment中得到以下错误:

 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) 

它recivies一个泛型类型的集合,因为列表是一个集合,它应该工作。

我也明确地把它铸造成一个List,但它仍然说同样的事情。

谢谢!

问题是泛型集合声明需要一个实际的类型。 但是,您正在使用没有指定类型的List <*>,并且编译器假定与Box关联的泛型类型是“Nothing”。

有几种方法可以解决这个问题。

  • 如果你知道一个特定的类型将提前使用它,你可以使用一个when语句做一个适当的List类型的智能转换,然后你将能够创建一个正确的Box实例,调用put()方法没有问题。

     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 ... } } 
  • 使用反射从Box中获取put()方法,然后对其进行调用。 这将绕过编译器的语义检查,但是稍微可疑,稍后可能会遇到问题。

     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) }