如何在 Kotlin 扩展函数中使用泛型

How to use Generics in Kotlin extension function

我有 2 个功能基本相同,所以我想创建一个扩展功能。

问题是我需要提取每个 class 的数据才能得到正确的结果,我想创建一个通用函数,并在这个函数内部决定哪个 class 成员访问内部 when 语句。

但是当我尝试在 when 语句中调用 T 时,我得到 Type parameter 'T' is not an expression

我做错了什么?

我的函数:

fun <T: Any> List<T>.extractWithSepreation(errorString: String): String {
    var errorString = "There is no available $errorString"

    if (this.isEmpty()) {
        return errorString
    }
    
    errorString = ""
    this.forEachIndexed { index, item ->
        when(T)
    }

}

错误消息几乎说明了一切。 T不是表达式,所以不能在when(...)中使用。 T只是指Listitem的class。

你不是说使用类似的东西吗:

when(item) {
   is ClassA -> doSomething()
   is ClassB -> doSomethingElse()
}

?