Search code examples
listinsertkotlinprependcons

Kotlin prepend element


I am searching for Kotlin alternative to:
(cons 1 '(2 3)) in lisp or
1 : [2, 3] in haskell or
1 :: List(2, 3) in scala,
(which all result in sth like [1, 2, 3])
so I can prepend an element to a List<T> (or any other list you can offer).

It will also be fine if one could provide O(1) head and tail Kotlin alternatives (I've found just first())


Solution

  • Any class which implements Deque will suitable for you, for example LinkedList:

    val linkedList = LinkedList(listOf(2, 3))
    linkedList.push(1)
    println(linkedList) // [1, 2, 3]
    

    Creating lists throught constructor LinkedList(listOf(2, 3)) in many places can be annoying, so feel free to write factory method:

    fun <T> linkedListOf(vararg elements: T): LinkedList<T> {
        return LinkedList<T>(elements.toList())
    }
    
    // Usage:
    val list = linkedListOf(2, 3)
    list.push(1)
    println(list) // [1, 2, 3]