android - 在 Kotlin 中构建 LinkedList 时出现类型推断问题

标签 android kotlin

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

Error:Error:line (21)Kotlin: Type inference failed: Cannot infer type parameter T in constructor Node(value: T#1 (type parameter of Node), next: Node? = ...) None of the following substitutions (T#2 (type parameter of LinkedList),Node?) (Int,Node?) can be applied to (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++
    }
}

谁能解释一下我做错了什么?

最佳答案

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

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

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

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

关于android - 在 Kotlin 中构建 LinkedList 时出现类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59114402/

相关文章:

Android Studio 构建风格

java - Android 相机示例 NullPointerException

android - android启动服务时,ui线程是否需要去等待才能启动?

java - 安卓工作室, "Unresolved Reference: activity_main"

java.lang.OutOfMemory错误: Failed to allocate a 571401228 byte allocation with 16777216 free bytes and 495MB until OOM

android - 在模拟器中打开wifi

android - 尝试使用android创建房间数据库,但不断出现依赖错误

android - 如何从 Webview 中访问摄像头?

android - 如何动态更改依赖项?

android - Kotlin Android Button.onClickListener 导致 NoSuchMethodError