Skip to content

Instantly share code, notes, and snippets.

@AndroidPoet
Created May 5, 2022 12:56
Show Gist options
  • Save AndroidPoet/0ae30894915f0506073cf7ffea4d3498 to your computer and use it in GitHub Desktop.
Save AndroidPoet/0ae30894915f0506073cf7ffea4d3498 to your computer and use it in GitHub Desktop.
Generics
class MutableStack<E>(vararg items: E) {
private var elements = items.toMutableList()
fun push(element: E) = elements.add(element)
fun peek(): E = elements.last()
fun pop(index: Int): E = elements.removeAt(index)
fun isEmpty() = elements.isEmpty()
fun size() = elements.size
override fun toString() = "MutableStack(${elements.joinToString()})"
}
fun <E> mutableStackOf(vararg elements: E) = MutableStack(*elements)
fun main() {
val stack = mutableStackOf(1, 2, 3, 4, 5, 6)
print(stack)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment