i try to add to the higher order function an lambda expression. but my question is : how can I implement the forEach function, which each element from the list with the passed Function action calls?
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) {
...
}
}
getbut callingactiononrunPointer.datarunPointer.datayou encounter while you loop. Also, what isclear()'s contract here? It seems to be really really weird: it returns an empty list but doesn't do anything withthislist.