【问题标题】:How to resolve "Not enough information to infer type variable" when one type variable not inferrable AND using wildcard on the other?当一个类型变量不可推断并且在另一个类型上使用通配符时,如何解决“没有足够的信息来推断类型变量”?
【发布时间】:2022-11-30 06:06:28
【问题描述】:

尝试将一些 Java 代码转换为 Kotlin,Java 代码包括对库方法 TableUtils.dropTable 的调用,该方法是用 Java 实现的。这个方法的 Java 方法签名是

public static <T, ID> int dropTable(ConnectionSource connectionSource, Class<T> dataClass, boolean ignoreErrors) throws SQLException

从 Java 调用该方法时,即使类型变量 ID 未知,它也可以正常编译。例如:

public void method(ConnectionSource connectionSource, Class<? extends IRecordObject> clazz) {
    try {
        TableUtils.dropTable(connectionSource, clazz, true); // this compiles fine
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

转换为 Kotlin 后,相应的函数编译失败,因为无法推断类型变量ID

fun method(connectionSource: ConnectionSource?, clazz: Class<out IRecordObject>) {
    try {
        TableUtils.dropTable(connectionSource, clazz, true) // compile error: "Not enough information to infer type variable ID"
    } catch (e: SQLException) {
        e.printStackTrace()
    }
}

我不知道如何显式指定类型变量,因为其中一个变量是通配符,并且在调用函数时不允许在类型变量中使用通配符。例如:

TableUtils.dropTable<out IRecordObject,Long>(connectionSource, clazz, true) // this also fails to compile, "Projections are not allowed on type arguments of functions and properties"

那么我如何在这里指定类型变量ID来让代码在Kotlin中编译呢?

【问题讨论】:

    标签: kotlin generics kotlin-interop


    【解决方案1】:

    ID 类型在函数签名中未使用,因此它是什么并不重要。对于 Kotlin 版本,您可以直接将任何类型放在那里以使错误消失。由于类型擦除,无论您使用哪种类型都不会影响编译后的代码。您可以 use an underscore 允许推断 T

    fun method(connectionSource: ConnectionSource?, clazz: Class<out IRecordObject>) {
        try {
            TableUtils.dropTable<_, Unit>(connectionSource, clazz, true)
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 2020-03-11
      相关资源
      最近更新 更多