gpt4 book ai didi

kotlin - 智能转换无法按预期运行

转载 作者:行者123 更新时间:2023-12-02 13:39:05 24 4
gpt4 key购买 nike

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

有两种方法可以解决此问题。

  • 如果您知道提前使用的一组特定类型,则可以使用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)
    }
  • 关于kotlin - 智能转换无法按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188634/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com