实现高阶函数和 lambda

Implement higher order functions and lambda

我尝试向高阶函数添加一个 lambda 表达式。但我的问题是: 我如何实现 forEach 函数,列表中的每个元素都传递 函数操作调用?

import java.lang.IndexOutOfBoundsException

    class LinkedList <T> {
        data class Node<T>(val data: T, var next: Node<T>?)

        private var first: Node<T>? = null


        fun addFirst(data: T) {
            val newNode = Node(data, first)
            first = newNode
        }

        fun isEmpty() = first == null

         fun clear(): Any {
           return LinkedList<T>().clear()
        }

        fun get(index: Int): Any {
            var position = 0
            var runPointer = first
            while (runPointer != null && position != index) {
                position += 1
                runPointer = runPointer.next
            }
            return runPointer?.data ?: throw IndexOutOfBoundsException()
        }

         
         
        fun forEach(action: (T) -> Unit) {  
            ...

        }
    }

好吧forEach是标准库中Iterrable的扩展函数

 fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

来源https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/common/src/generated/_Collections.kt

当您使用 first: Node 时,您应该这样做:

fun forEach(action: (T) -> Unit) {
    var p = first
    while (p != null) {
        action(p.data)
        p = p.next
    }
}