Search code examples
dartgenericsstackreturn-value

How to check if stack is empty in generic class


I have a generic class Stack having push and pop method. I want to check if stack is empty before the pop method is invoked on the list and return a value to indicate the user that list is empty.

class Stack<T> {
  final List<T> _items = [];

  void push(T item) => _items.add(item);

  // T pop() => _items.removeLast(); 

  // Return a value or something to indicate that the stack is empty
  // Doesn't work
  T pop() => _items.isNotEmpty ? _items.removeLast() : (print('List is empty'), null);

  void display() => _items.forEach(print);
}

Solution

  • Using ? with return type solved my problem. It enable the null to be returned when Stack is empty.

    T? pop() => _items.isNotEmpty ? _items.removeLast() : null;