compiler-errorsconstantseiffelclass-constants

Eiffel: once function has generic or anchored result. Trying to create constants


I'm trying to create some terminal logging colors to be able to see clearer my errors. Doing that it seems to me obvious that I'd have to create constants like followings. As I don't want to create an instance each time I call my constant, it makes sense for me to do something like that, but the compiler doesn't seem to have the same conception as me...

A once function has generic or anchored result what is an anchored result?

As the compiler has always the last word and me the forelast, why am I wrong and is he right??

class
    TERMINAL_COLOR

create
    make

feature -- Initialization

    make (a_fg: like foreground; a_bg: like background)
        do
            foregound := a_fg
            background := a_bg
        end

feature -- Status report

    foreground: INTEGER

    background: INTEGER

feature -- Colors

    Black: like Current
        once -- compiler doesn't agree with me
            create Result.make (30, 40)
        ensure
            instance_free: class
        end

end

Solution

  • An anchor type is when you use the "like feature" (note you can also use "like {FOO}.bar" ).

    Also, don't forget the Once is "once per class" (not by type). That's why the result type for a once function could not be using any formal generic. For instance

    class FOO [G]
    feature
        bar: STRING
            once
               Result := generating_type
            end
    end
    

    (create {FOO [INTEGER]}).bar will return the same object as (create {FOO [STRING]}).bar.

    So, now if bar would return G in class FOO, it would cause trouble as there is no way to return a value that conforms to any formal (INTEGER, STRING, ...).

    That's why generic are forbidden for once result type.

    The same logic applies to anchor type such like feature_name, as feature_name could be redefined in descendant with other types.