Web Development With HHVM and Hack 18: Mixed

Mike Abelar
2 min readApr 29, 2020

--

In the last tutorial, we went over types and null: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-17-types-and-null-be29a7d36ab5. In this tutorial, we will go over mixed.

What is Mixed?

Mixed is a nullable type (meaning it can take on the value of null) and is mainly used to represent a parameter that can take on multiple types.

Let us explore mixed by creating a directory for this tutorial. Inside the directory, start with touch .hhconfig . Then, touch mixed.hack to create a file for us to explore Mixed. Inside the file, paste the following contents:

function print_vec(vec<mixed> $elements) : void {
foreach ($elements as $element) {
print($element);
print("\n");
}
}
<<__EntryPoint>>
function main() : noreturn {
$elements = vec[5, "hi", true];
print_vec($elements);
exit(0);
}

Inside the main function, we have a vec of different types of elements: an int, a string, and a bool. We then pass the vec to a function print_vec which takes in vec<mixed> . The mixed is used to denote that there will be multiple types. When run using hhvm mixed.hack , we get:

5
hi
1

To understand the importance of vec, let’s run hh_client mixed.hack :

No errors!

Now, let us change

vec<mixed> $elements

to

vec<int> $elements

and run hh_client mixed.hack :

Typing[4110] Invalid argument

We get an invalid argument error. That is because we need to use mixed to represent a vec of different types.

Note: if you have a vec/dict of floats and ints, use num. Similarly, if you have a vec/dict of ints and strings, use ArrayKey. It is better to use these more specific types rather than mixed.

In the next tutorial, we cover the pipe operator: https://medium.com/@mikeabelar/web-development-with-hhvm-and-hack-19-pipe-operator-cf6aa739cd8a

--

--