ArrayList.set 提示 第二个参数 element 类型是 NoThing ?

2022-10-08 11:27:41 +08:00
 coderstory
  fun setValue(variables: Map<String, Any>, value: Any?) {
        val instance = operand.eval(variables) ?: throw NullPointerException("instance is null")

        if (instance is LogicList<*>) {
            instance.set(property.key.replace("[", "").replace("]", "").trim().toInt(), value)
        } else {
            throw IllegalArgumentException("变量 ${(operand as Variable).key} 不是数组")
        }
    }
    

代码如上 instance.set 方法 idea 提示我第二个参数 element 是 NoThing 类型 导致我 set 方法无法调用

Kotlin: Type mismatch: inferred type is Any? but Nothing was expected

直接编译 报了如上错误 instance 本身是 Any?类型的,由于做了 null 校验,所以是 Any 类型的。 LogicList 是 ArrayList 的扩展类,set 方法又 List 提供的。 这边我不太清楚要怎么改了,我本身也不太懂 kotlin 。

1415 次点击
所在节点    Kotlin
6 条回复
yazinnnn
2022-10-08 13:42:36 +08:00
class LogicList:ArrayList<Any?>()
coderstory
2022-10-08 13:50:52 +08:00
@yazinnnn

class LogicList<E> : ArrayList<E> {

原本是这样的 E 改成 Any 一样的
coderstory
2022-10-08 14:00:01 +08:00
@yazinnnn



class LogicList<E> : ArrayList<E> {

constructor()
constructor(collection: Collection<E>) : super(collection)

var currentRowNumber = -1L
val current: E?
get() {
return if (size != 0) {
get((if (currentRowNumber == -1L) 0L else currentRowNumber).toInt())
} else {
null
}
}
val length: Long get() = size.toLong()
val empty: Boolean get() = isEmpty()

@JvmField
val List = this

fun next() = currentRowNumber++


fun reset() {
currentRowNumber = -1L
}
}
coderstory
2022-10-08 14:06:42 +08:00
简化一下

fun setValue( ) {
val instance: Any = aaa();

val a: List<*> = instance as List<*>;

if(instance is MutableList<*>){
instance.set(1,2) // 在这里 第二个参数 element 的类型提示是 Nothing 导致无法编译
}
}

fun aaa():Any{
return mutableListOf(1,2,3);
}
yazinnnn
2022-10-08 14:12:16 +08:00
LogicList 不要带泛型,继承 ArrayList<Any?>()
Leviathann
2022-10-08 14:30:23 +08:00
kotlin 和 java 的泛型没区别
这里用 is 判断以后必须手动转型
(instance as LogicList<Any?>)[property.key....] = value
并且 suppress UNCHECKED_CAST
jvm 上泛型的尽头就是 @Suppress("UNCHECKED_CAST")

另外这里的 [ 和 ] 如果是前缀和后缀的话可以直接改用 removeSurrounding
还有第一个 throw 和!!没区别,没附加任何有用的上下文信息,建议把 variable 打印一下

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/885193

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX