Question: Why Java not have an union type

Netroby hufeng1987 at gmail.com
Fri Dec 11 22:39:47 UTC 2020


For short, let's see the RFC document from the PHP community.

https://wiki.php.net/rfc/union_types_v2

for a small piece of code

```

class Number {
    private int|float $number;

    public function setNumber(int|float $number): void {
        $this->number = $number;
    }

    public function getNumber(): int|float {
        return $this->number;
    }
}

```
The union type seems to have it's benefits.

Do less code, get more flexibility.

We limit two Type: Int or float.
Our function only accepts these two type inputs. and returns the same type .

As for now, we can use generics. but it's too heavy .
generics normally come with Class level, but union type can be Function level .






Appreciate your time.
----------------------------
Netroby


More information about the jdk-dev mailing list