How can I use stack in Kotlin?

Kotlin 1.3.70 introduced the kotlin.collections.ArrayDeque class, which functions as both a queue and a stack, like Java’s java.util.Deque (Deque meaning “double-ended queue”). It was created out of a necessity for a multiplatform ArrayDeque implementation.

val stack = ArrayDeque(listOf(1, 2, 3)) // stack: [1, 2, 3]
stack.addLast(0)                        // stack: [1, 2, 3, 0]         (push)
val value = stack.removeLast()          // value: 0, stack: [1, 2, 3]  (pop)

Note that if an ArrayDeque is empty when you call removeFirst or removeLast, it will throw a kotlin.NoSuchElementException. If you don’t want to check the size of your deque every time you need to access it, then you should use the removeFirstOrNull and removeLastOrNull functions.


Optional Snippets

ArrayDeque constructor function:

inline fun <T> arrayDequeOf(vararg elements: T) = ArrayDeque(elements.toList())
// ...
val stack = arrayDequeOf(1, 2, 3)

Stack-like ArrayDeque calls:

inline fun <T> ArrayDeque<T>.push(element: T) = addLast(element) // returns Unit

inline fun <T> ArrayDeque<T>.pop() = removeLastOrNull()          // returns T?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)