coderstory
V2EX  ›  Kotlin

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

  •  
  •   coderstory · Oct 8, 2022 · 3037 views
    This topic created in 1321 days ago, the information mentioned may be changed or developed.
      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 。

    6 replies    2022-10-08 14:30:23 +08:00
    yazinnnn
        1
    yazinnnn  
       Oct 8, 2022
    class LogicList:ArrayList<Any?>()
    coderstory
        2
    coderstory  
    OP
       Oct 8, 2022
    @yazinnnn

    class LogicList<E> : ArrayList<E> {

    原本是这样的 E 改成 Any 一样的
    coderstory
        3
    coderstory  
    OP
       Oct 8, 2022
    @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
        4
    coderstory  
    OP
       Oct 8, 2022
    简化一下

    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
        5
    yazinnnn  
       Oct 8, 2022
    LogicList 不要带泛型,继承 ArrayList<Any?>()
    Leviathann
        6
    Leviathann  
       Oct 8, 2022
    kotlin 和 java 的泛型没区别
    这里用 is 判断以后必须手动转型
    (instance as LogicList<Any?>)[property.key....] = value
    并且 suppress UNCHECKED_CAST
    jvm 上泛型的尽头就是 @Suppress("UNCHECKED_CAST")

    另外这里的 [ 和 ] 如果是前缀和后缀的话可以直接改用 removeSurrounding
    还有第一个 throw 和!!没区别,没附加任何有用的上下文信息,建议把 variable 打印一下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5694 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 02:30 · PVG 10:30 · LAX 19:30 · JFK 22:30
    ♥ Do have faith in what you're doing.