[Kotlin] Generics basic

//vararg: just like ...args in js
class Stack<T>(vararg val items: T) {
    
    val elements = items.toMutableList()
    
    fun push(element: T) {
        elements.add(element)
    }
    
    fun pop(): T? {
        if (!isEmpty()) {
            return elements.removeAt(elements.size - 1)
        }
        return null
    }
    
    fun isEmpty(): Boolean {
        return elements.isEmpty()
    }
}


fun main() {
    val stack = Stack(3,4,2,6)
    println(stack.pop())
    println(stack.pop())
    println(stack.pop())
    println(stack.pop())
    println(stack.pop()) // null
}

 

posted @ 2020-10-14 02:40  Zhentiw  阅读(46)  评论(0编辑  收藏  举报