【问题标题】:Type not recognized with generics method in KotlinKotlin 中的泛型方法无法识别类型
【发布时间】:2018-10-09 07:42:52
【问题描述】:

我有这个通用方法的接口:

interface IInterface {
    fun <T> test(body: T)
}

我想这样实现这个接口:

class MyClass: IInterface {
    override fun <JsonObject> test(body: JsonObject) {
        if (body is com.google.gson.JsonObject) {

        }
    }
}

我的问题是类型 JsonObject 无法识别,例如“com.google.gson.JsonObject”。所以我可以在我的编译器(intelliJ)中编写这段代码而不会出错。

override fun <NotExistingClass__> test(body: NotExistingClass__) {

那么,如何从 Gson 中为 JsonObject 定义 T 的类型呢?此代码不起作用:

override fun <com.google.gson.JsonObject> test(body: com.google.gson.JsonObject)

谢谢

【问题讨论】:

  • 在你的情况下,你需要使用泛型类而不是使用泛型方法。

标签: spring spring-boot generics kotlin


【解决方案1】:

这个interface

interface IInterface {
    fun <T> test(body: T)
}

不是通用的,但它有一个通用方法。如果您想使其通用,请执行以下操作:

interface IInterface<T> {
    fun test(body: T)
}

那么您的实现将如下所示:

class MyClass: IInterface<JsonObject> {
    override fun test(body: JsonObject) {
        if (body is com.google.gson.JsonObject) {

        }
    }
}

如果您出于某种原因仍需要泛型方法,则必须在每个调用站点传递泛型类型参数:

someInstance.test<JsonObject>(obj)

【讨论】:

  • 因为您想将泛型类型参数传递给方法在其声明中。您只能在调用站点向其传递参数。
猜你喜欢
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多