Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Introduce dict<Tk, Tv> array type #6452

@dlreeves

Description

@dlreeves

This is a part of the Hack array proposal

A dict array is a container mapping a valid arraykey to a value. This mirrors the behavior of the Map class. This will be an array at runtime with extra restrictions to allow it to be used safely like a Map from the type checkers perspective. This focuses mainly on the desired runtime behavior, but if there are questions for how it will interact with the type checker I'll be happy to discuss.

Literal Constructor

A dict is constructed using the literal expression dict[].

$dict = dict[]; // Empty dict-array
$dict = dict['a' => 1, 'b' => 2, 'c' => 3]; // dict-array of 3 elements

This is a static expression, so it can be used in a static initializer.

class C {
  public static $dict = dict[
    'a' => 1,
    'b' => 2,
    'c' => 3,
  ];
}

Traversable Constructor

A dict can also be constructed from any KeyedTraversable type, using the traversable constructor.

$array = array('a' => 1, 'b' => 2, 'c' => 3);
$dict = dict($array); // constructs dict-array from another array

Adding Elements

Appending an element to a dict will be a type checker error, but will still work at runtime. The array set operator is used to add a new element to the dict, similar to PHP arrays. However the key will not be coerced in any way. If the key is a string, then we will store a string and not convert it to an int if it is int-like.

$dict = dict[];
$dict[0] = 1; // Allowed
$dict['0'] = 2; // Allowed - does not override 0 key
$dict[] = 3; // Type Error

Removing Elements

Removing an element from a dict is identical to removing an element from a PHP array, namely by using unset.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions