Ferit
Ferit

Reputation: 9657

MATLAB - ENUM - Cannot call the constructor of 'X' outside of its enumeration block

I am trying to create an enum just like this:

classdef MoleculeType < media.Molecule
    enumeration
        O2 (media.ElementalComposition(media.Atom(media.AtomicWeight.Oxygen), int32(2)))
    end

end

Inherited Molecule Class:

classdef Molecule < handle

    properties(SetAccess = immutable)

        chemicalComposition

    end

    ...

    methods

        function obj = Molecule(composition)
            obj.chemicalComposition = composition;
        end

    ...

    end

    ...

end

When I try to get an instance from MoleculeType, I get "Cannot call the constructor of 'media.MoleculeType' outside of its enumeration block." error. I couldn't figure out where it tries to call MoleculeType constructor so I get this error, because there is no reference to MoleculeType constructor in my code.

Please help me out. Thanks in advance.

Hint: I created enum classes without error before and they were having primitive values inside (e.g. O2(32)). Problem arise when I try to use object types inside enumerations (like in this question: O2(media.ElementalComposition)). I searched this in MATLAB documentation, there is no example. Documentation neither provide an example nor say that it is not supported.

Upvotes: 1

Views: 4876

Answers (1)

Andy Campbell
Andy Campbell

Reputation: 2187

How are you trying to create the enum instance? The following works for me, unless I construct it the wrong way at the command line:

Molecule.m (Simplified)

classdef Molecule
    properties(SetAccess=immutable)
        Composition
    end
    methods
        function m = Molecule(composition)
            m.Composition = composition;
        end
    end
end

MoleculeType.m

classdef MoleculeType < Molecule
    enumeration
        O2 (32)
    end
end

Creating/referencing the enum

>> MoleculeType % wrong way
Error using MoleculeType
Cannot call the constructor of 'MoleculeType' outside of its enumeration block.

>> MoleculeType.O2 % right way

ans = 

    O2

>> 

Hope that helps!

Upvotes: 2

Related Questions