Re: [PHP-DEV] [Discussion] Revisiting typed closures

[email protected] (Matheus Martins)
Newsgroups php.internals
Message-ID <CAAZKEqiMLHe=4GL=LE-krTHbRJYtd6_9Od2Q0i5ZBehAqXUXBA@mail.gmail.com>
> I would rather wait for generics and possibly make Closure a generic type.

Fair point, but I am worried that's misleading, and I would keep the two
separate.

Generics are a much larger and more contentious topic; typed closure is a much
smaller topic: a runtime shape check on a Closure value at the boundary, nothing
more.

The concrete benefit is typing the callback a higher-order method takes,
so a mismatched map/filter callback is caught at the call site rather than deep
inside the operation (or only by static analysis):

```php
// expected signature: (int) => bool
public function filter(Closure(int): bool $pred): static;

// ok
$nums->filter(fn(int $n): bool => $n % 2 === 0);

// TypeError: string not expected
$nums->filter(fn(string $s): bool => $s !== '');
```

Typed closures neither need generics nor blocks them. In fact, eventually typed
closures will support generics. But I would rather keep these topics separate.

On its own, is a runtime-checked closure signature something you would find
useful?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.