Implement a typed stack
Build a last-in, first-out stack whose empty case is explicit. This exercise restricts elements to non-null values so null can unambiguously mean an empty stack.
class Stack<T : Any> {
private val values = mutableListOf<T>()
val size: Int get() = values.size
fun push(value: T) { values.add(value) }
fun popOrNull(): T? = if (values.isEmpty()) null else values.removeAt(values.lastIndex)
fun peekOrNull(): T? = values.lastOrNull()
}
The backing collection is private. Exposing it would let callers bypass stack ordering. This implementation does not promise thread safety or constant-time behavior on every imaginable list implementation; it uses Kotlin's mutable-list factory and end operations.
Acceptance checks
Push A then B, peek B without reducing size, pop B then A, and verify an additional pop returns null. Repeat with integers. Compile-time type checking should reject pushing an integer into Stack<String>.
Extension: support nullable elements using a sealed pop result distinguishing Empty from Present(null), rather than overloading null with two meanings.