Kotlin prepend element

Columpio picture Columpio · Mar 19, 2017 · Viewed 15.6k times · Source

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())

Answer

Strelok picture Strelok · Mar 20, 2017

I think the easiest would be to write:

var list = listOf(2,3)
println(list) // [2, 3]
list = listOf(1) + list
println(list) // [1, 2, 3]

There is no specific tail implementation, but you can call .drop(1) to get the same. You can make this head\tail more generic by writing these extension properties:

val <T> List<T>.tail: List<T>
  get() = drop(1)

val <T> List<T>.head: T
  get() = first()

Then:

val list = listOf(1, 2, 3)
val head = list.head
val tail = list.tail

Some more info: Kotlin List tail function