Why is record considered product type but class not so in java?

246 views Asked by At

Java 16 is going to officially deliver the record feature, which according to one of the authors is a form of product types.

I understand record's internal states range from a Cartesian product space constructed from the member fields, thus is an example of product type. But isn't it the same with traditional OOP classes? Why rarely do programmers consider classes to be an example of product type?

(In fact, I tend to feel that with inheritance, superclass is also a weak kind of sum type for its subclasses.)

1

There are 1 answers

5
Stephen C On

From a type theory perspective, a cartesian product type is a set of tuples consisting of the values of the individual "field" types. It does not allow for mutation. A Java 14+ record type is immutable, so there is a good match between record and cartesian product types.

From the same perspective, an object type has to allow for mutation. However, classical type theory does not allow (mathematical) values to mutate. That means that an object type has to be modeled as a set of functions (lambda expressions) that map from one state of an object to the next state.

(The same approach is used to model mutation in a pure functional language. Mutation is modeled by creating a new state / environment / context from a previous one.)

So ....

But isn't it the same with traditional OOP classes?

No; see above.

Why rarely do programmers consider classes to be an example of product type?

Well, basically because they would be wrong to do that.

Type theory is not a matter of opinion. It is mathematics. A mathematical proposition is either provably correct or not. A proposed type theory for as programming language is either provably correct (within certain constraints) or not. Any proposed type theory for OO that does not support mutation is clearly incorrect, because mutation of an object's state is central to OO.

There are good textbooks on type theory. If you really want to understand this stuff, you should buy one and read it.