0

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) {  
            ...

        }
    }
3
  • Same way you implemented get but calling action on runPointer.data Commented May 12, 2021 at 16:26
  • I agree with @al3c, you just need to call action on each of the runPointer.data you encounter while you loop. Also, what is clear()'s contract here? It seems to be really really weird: it returns an empty list but doesn't do anything with this list. Commented May 12, 2021 at 17:16
  • can you show me an example with each of the functions, because it doesn't work for me Commented May 12, 2021 at 17:38

2 Answers 2

2

As you are using a first: Node you should do:

fun forEach(action: (T) -> Unit) {
    var p = first
    while (p != null) {
        action(p.data)
        p = p.next
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Well forEach is extension function of Iterrable as in std lib

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

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

2 Comments

ok thanks but how can i do it without the iterable. How should i write it in here fun forEach(action: (T) -> Unit) {
Well you can use it with out Iterrable like fun forEach.. but this is applicable for only LinkedList type in other word the variable you call must be a child of the super class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.