The Crystal Programming Language Forum

Array allow child class types

Hello, I’m with a problem actually, I have a class CommandLineOption. And I made some others class inherit from CommandLineOption.

CommandLineOption have “option” as parameter, and this parameter is an array with others CommandLineOption items. But how can I allow this array to accept CommandLineOption class and their class are inherit them?

Normally, it’s this:

But this Array allow only CommandLineOption, not classes inherit of it

Array(ISM::CommandLineOption) allows instances of that type and its children. I think you’re running into Inheritance - Crystal. But it’s hard to say without some examples/errors.

Hmmmm… yes normally, but it’s strange because I have this bug. It’s my problem actually:

~/Documents/Programmation/ISM ❯❯❯ crystal software install                            ✘ 1 master ✖ ✱ ◼
Showing last frame. Use --error-trace for full trace.


 17 | @options = options
Error: instance variable '@options' of ISM::CommandLineOption must be Array(ISM::CommandLineOption), not Array(ISM::Option::SoftwareInstall)

But I’m sure what you said is true, because I have one other class do something similar, and I don’t have this problem.

Normally, I initialize the value of my child class with this:

[ ]

But if I don’t do that:
[ ] of ISM::CommandLineOption
It don’t work. But it’s not very clean (I think) like that.

This confirms my suspicion. Unfortunately this is best you can do at the moment. I’d checkout that link I posted for more details.

I think it’s not really proper, no ?

What isn’t proper? As stated in the link, [ ] is a Array(ISM::Option::SoftwareInstall) even if that type inherits from ISM::CommandLineOption. If you want an array of child types to be typed as the parent class you need to use of ISM::CommandLineOption. That’s just how things work at the moment.

Ah okay. I wasn’t sure. Thanks you very much