【问题标题】:Type inference issue while building a LinkedList in Kotlin在 Kotlin 中构建 LinkedList 时出现类型推断问题
【发布时间】:2019-11-30 08:10:44
【问题描述】:

我正在尝试在 Kotlin 中从头开始创建 LinkedList 数据结构。在构造 Node 对象时,它不允许我将 head 分配给下一个参数并给出以下错误:

Error:Error:line (21)Kotlin: Type inference failed: Cannot infer type 构造函数节点中的参数 T(值:T#1(类型参数的 节点),下一个:节点? = ...) 没有以下替换 (T#2 (LinkedList的类型参数),Node?) (Int,Node?) 可以 应用于 (Int,Node?)

Node.kt

data class Node<T>(var value: T, var next: Node<T>? = null) {
    override fun toString(): String {
        return if (next != null) {

            "$value -> ${next.toString()}"

        } else {

            "$value"

        }

    }
}

LinkedList.kt

class LinkedList<T> {

    private var head: Node<T>? = null
    private var tail: Node<T>? = null
    private var size = 0

    fun isEmpty(): Boolean {
        return size == 0
    }

    override fun toString(): String {
        if (isEmpty()) {
            return "Empty List"

        } else {
            return head.toString()
        }
    }

    fun push(value: T) {
        head = Node(value = 5, next = head)
        if (tail == null) {
            tail = head
        }
        size++
    }
}

有人可以解释我在这里做错了什么吗?

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    在您的 LinkedList::push(value: T) 方法中,您可以:

    head = Node(value = 5, next = head)
    

    我不确定value = 5 来自哪里(也许您正在调试),但它应该是:

    head = Node(value = value, next = head)
    

    【讨论】:

    • 发生在我们所有人身上 :) 我同意您得到的错误根本无法理解。
    猜你喜欢
    • 2022-08-18
    • 2019-09-05
    • 1970-01-01
    • 2017-08-01
    • 2023-03-17
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多