gpt4 book ai didi

android - 如何在Kotlin扩展功能中使用泛型

转载 作者:行者123 更新时间:2023-12-02 13:10:40 26 4
gpt4 key购买 nike

我有2个功能基本上可以完成相同的工作,因此我想创建一个扩展功能。
问题是我需要提取每个类的数据以获得正确的结果,我想到了创建一个泛型函数,并在该函数中决定在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仅指itemList的类。
您不是说要使用类似的方法:

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

关于android - 如何在Kotlin扩展功能中使用泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63466015/

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