Google News
logo
Hack - Interview Questions
What are the different types of annotations that can be used in Hack code?
In Hack, you can use various types of annotations to provide additional information and instructions to the type checker, tools, and other developers who work with your code. Here are some common types of annotations used in Hack code:

1. Type Annotations : Type annotations specify the expected types of variables, function parameters, function return types, class properties, and class methods. You can use scalar types (int, string, bool, float), compound types (arrays, maps, sets, tuples), nullable types, generics, and user-defined types (classes, interfaces, traits) in type annotations.
function greet(string $name): string {
  return "Hello, ".$name;
}​

In the above example, `string` is used as a type annotation for both the parameter `$name` and the return type.

2. Nullable Annotations : Nullable annotations indicate that a variable or expression can accept `null` in addition to the specified type. This is denoted by adding a `?` before the type annotation.
function findUserById(int $id): ?User {
  // ...
}​

In the above example, the function `findUserById` can return either a `User` object or `null`.

3. Constant Annotations : Constant annotations specify that a variable is a constant and cannot be reassigned. You can use the `const` keyword to annotate constants.
const int MAX_COUNT = 10;​

In the above example, `MAX_COUNT` is annotated as a constant of type `int` with a value of 10.
4. Enum Annotations : Enum annotations define enumerations, which are a set of named constant values. You can use the `enum` keyword to annotate an enumeration.
enum UserRole: string {
  const ADMIN = 'admin';
  const USER = 'user';
}​

In the above example, `UserRole` is an annotated enumeration with two constant values: `ADMIN` and `USER`.

5. Generic Annotations : Generic annotations allow you to specify generic types for classes, interfaces, and functions. You can use angle brackets (`< >`) to provide type parameters.
class Stack<T> {
  // ...
}​

In the above example, `T` is a generic type parameter for the `Stack` class.

6. Override Annotations : Override annotations indicate that a method in a subclass overrides a method in its parent class or interface. You can use the `<<__Override>>` annotation to specify this.
class ChildClass extends ParentClass {
  <<__Override>>
  public function someMethod() {
    // ...
  }
}​

In the above example, the `someMethod` in `ChildClass` is annotated as overriding the corresponding method in `ParentClass`.
Advertisement