List.pop() how to make use of it?

I populate a list from an array

type Card = {
            getName: () -> Text;
            getValue: () -> Nat;
        };
private let cards:[var Card] = Array.init(numberOfCards, Cards.Card("","",0));
private var cardsToDeal: List.List<Card> = List.fromVarArray<Card>(cards);

public func deal(): Card {
    let (card, list) = List.pop<Card>(cardsToDeal);
    Debug.print(debug_show(cards[0].getName()));
    Debug.print(debug_show(card.getName()));
}

This works:
Debug.print(debug_show(cards[0].getName()));

This doesn’t:
Debug.print(debug_show(card.getName()));

and errors with:

type error [M0070], expected object type, but expression produces type ?Card/1

What does the List.pop() return?

List.pop returns an optional value as indicated by the ? in the error. A ?Card is a value that is either null or a Card. This is because the List could be empty, in which case there would be no Card that pop could return. See the documentation for Option in the base library for the different ways of working with these values: Option :: Internet Computer

The section on error handling and options is more thorough, but probably a little overkill for the problem you’re looking at right now.

3 Likes

ty!

this worked just fine :slight_smile:

switch(card) {
    case (null) {};
    case (?card) {
        Debug.print(debug_show(card.getName()));
    }
}