Inheritance and arrays
Steven Schveighoffer
schveiguy at gmail.com
Mon Jul 3 15:41:08 UTC 2023
On 7/3/23 7:37 AM, Arafel wrote:
> That's very clearly an implementation detail leaking: the semantics of
> the language shouldn't depend on how interfaces and classes are
> implemented.
It's a semantic detail -- casting an array does *not* make a copy, and
an array is not a complex object. It's just a block of data.
And so it only succeeds if the binary representation can properly be
reinterpreted.
This is the same for all array types, not just class/interfaces:
```d
int i = 1;
long x = i; // ok
int[] a = [1];
long[] b = a; // error
```
If Java works, it means that Java either handles the conversion by
making a copy, or by properly converting on element fetch/store based on
type introspection. It also might use a different mechanism to point at
interfaces.
You might want it to be similar, but there are tradeoffs. With D,
though, there is always the possibility of getting what you want by
adding a specialized type. Indeed, if you are just going to *read* the
definition, a map would work:
```d
auto ii = cc.map!(function I(C c) => c);
I i = ii[0]; // ok
```
However, if you plan to write the definition as well, you need a more
specialized type.
It's all doable, though.
> I find it most unexpected and confusing and, assuming it won't change
> anytime soon, I think it should at the very least be **clearly**
> documented. And the cast forbidden, since it can't possible work between
> classes and interfaces.
It is documented:
https://dlang.org/spec/arrays.html#implicit-conversions
However, the interface conversion is not covered, and it's a bit
nebulous as to what is specifically covered with classes/interface.
I think it could be improved.
> Honestly, this severely limits the usefulness of interfaces, and for
> hierarchies of classes it might be much better to switch to abstract
> classes.
>
> BTW, even for (abstract) classes you need a cast:
...
>
> Shouldn't `ii = cc` work in this case?
I think this has been discussed in another part of the thread. But I did
want to point out that an implicit cast to `const` base type array is
possible (not for interfaces, since the binary representation is different).
-Steve
More information about the Digitalmars-d-learn
mailing list