6

The docs are pretty light. The interface looks almost identical to an array.

When should I prefer a dict?

hurrymaplelad
  • 26,645
  • 10
  • 56
  • 76

2 Answers2

7

Arrays in php are meant to be both dictionaries and vectors. That's very confusing. Also in arrays, there is key coercion to integer. Which is more confusing.

Hack dicts are meant to remove the ambiguity and fix the problem with the keys.

Pablo Alcubilla
  • 363
  • 2
  • 5
5

To expand a bit:

  • Hack is diverging from PHP - ultimately, this is likely to mean that PHP arrays are either removed from the language at some point, or become rather inconvenient. Ultimately, if you're writing Hack, you should prefer Hack dict/vec/keyset over PHP arrays.
  • on Pablo's point, array<string, Tv> is a lie, and breaks Hack's type system. array_keys(['123' => 'bar'])[0] is an int, not a string. This isn't the case for dict or keyset.
  • the Hack Standard Library provides a consistent API for Hack Arrays. While most of the container functions can take PHP arrays as input, they will produce Hack arrays.

A more interesting question is "Hack arrays" (vec, dict, keyset), vs "Hack collections" (Map, Set, Vector) and their const/immutable relatives. This is pretty contentious.

The main differences are that they are objects, not values; this effectively means that functions you pass them to can mutate them, whereas vec/dict/keyset act as if they are copy-on-write. The copy-on-write behavior is usually desired, but occasionally, object behavior is desired.

This is where it becomes contentious: - some argue that if you want object-like semantics, you should use Hack Collections - I personally think it's better to wrap it in a 'Ref' class: e.g. class Ref<T> { public function __construct(public T $value) {} - and operate on $ref->value using the standard API; this lets you use the same API (the HSL) for both, rather than the slightly different one that collection objects have

Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192
Fred Emmott
  • 194
  • 1
  • 6