[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
}
原文地址:https://www.cnblogs.com/Answer1215/p/13812591.html