Skip to content

Instantly share code, notes, and snippets.

@AndyBowes
Created August 1, 2017 16:52
Show Gist options
  • Save AndyBowes/cbb2763a8aadbf9f0248f5984bb3a94a to your computer and use it in GitHub Desktop.
Save AndyBowes/cbb2763a8aadbf9f0248f5984bb3a94a to your computer and use it in GitHub Desktop.
Kotlin Stack Implementation
class Stack<T>{
val elements: MutableList<T> = mutableListOf()
fun isEmpty() = elements.isEmpty()
fun count() = elements.size
fun push(item: T) = elements.add(item)
fun pop() : T? {
val item = elements.lastOrNull()
if (!isEmpty()){
elements.removeAt(elements.size -1)
}
return item
}
fun peek() : T? = elements.lastOrNull()
override fun toString(): String = elements.toString()
}
fun <T> Stack<T>.push(items: Collection<T>) = items.forEach { this.push(it) }
@CoreyShupe
Copy link

why is push written outside of the class decleration

@Ajimi
Copy link

Ajimi commented Jan 24, 2019

It's an extension function

@WaheedNazir
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment