What is the BoxT statement for?

2

I was checking out the Hack documentation .

I know this language is a modification of PHP to introduce type checking.

I saw that they put this example to demonstrate the use of classes, I think it has to do with defining primitive types.

class Box<T> {
  protected T $data;

  public function __construct(T $data) {
    $this->data = $data;
  }

  public function getData(): T {
    return $this->data;
  }
}

I'm used to the PHP classes and have never seen a statement like this before.

It seems that it only accepts the letter T , because I did tests here on my machine with other names, but it generated errors.

After all, what does this Box<T> statement mean?

    
asked by anonymous 17.06.2016 / 20:56

2 answers

2

This is about generic programming , which is fundamental in statically typed languages. So it has in Hack and not in PHP.

Here the T functions as a super variable and will have a value replaced later - this value can only be a data type. When you are instantiating this class you will have to tell us what kind of data the instance will work on, after all in statically typed language all data needs a fixed type. This class can pack data of any kind. Imagine how crazy it would be to create a new class for every type you need.

In a dynamic language it is simpler because it creates an indirection and handles the data in a generic way and resolves at runtime, which can work or not. In static language you need to resolve at compile time giving more security and performance.

It is a way to instruct the compiler to use this class in a special implementation in each instantiation. Then the compiler will automatically generate a new version of the class for each type actually instantiated in your application. All places where you have T will receive the type to be instantiated.

If you instantiate with a int (eg, new Box<int> ) the generated inner class (you do not need to know about it) will look something like this:

class BoxInt {
  protected int $data;

  public function __construct(int $data) {
    $this->data = $data;
  }

  public function getData(): int {
    return $this->data;
  }
}

You can use the identifier you want there, because you can have several in classes that depend on more than one type. But it must have consistency of its use in every class. The error may be because it spoke to change in other places where it still had T , but I do not know, this was not posted, I can only respond by speculating.

    
17.06.2016 / 21:06
0

In C # this notation is for you to instantiate the same class, but modify the types. It's a generic type statement. For example ...

new Box<string>();

and

new Box<int>();

Generate the object type Box to internally $ date will be string in the first case and int in the second.

    
17.06.2016 / 21:03