Created
August 1, 2017 16:52
-
-
Save AndyBowes/cbb2763a8aadbf9f0248f5984bb3a94a to your computer and use it in GitHub Desktop.
Kotlin Stack Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) } |
It's an extension function
Official kotlin doc, this might help.
https://play.kotlinlang.org/byExample/01_introduction/06_Generics
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why is push written outside of the class decleration