【问题标题】:Smart cast doesn't work as expected智能投射无法按预期工作
【发布时间】:2017-11-09 06:21:26
【问题描述】:

我有以下 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)

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

我也明确地将它转换为一个列表,但它仍然说同样的事情。

谢谢!

【问题讨论】:

    标签: kotlin kotlin-interop


    【解决方案1】:

    问题在于泛型 Collection 声明需要一个实际类型。但是,您使用的 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)
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多