Search code examples
hashtableeiffel

Access HASH_TABLE element eiffel


I have this simple code, I'd like to access an element in an ARRAYED_SET what is in a HASH_TABLE, but I get an error:

Error: target of the Object_call might be void.
What to do: ensure target of the call is attached.

here's my code:

class
APPLICATION

inherit
    ARGUMENTS

create
    make

feature {NONE}
make
local

    elem: ARRAYED_SET[INTEGER]
    table: HASH_TABLE[ARRAYED_SET[INTEGER], INTEGER]
do
    create elem.make (3)
    create table.make (1)

    elem.put (4)
    table.put (elem, 1)

    table.at (1).go_i_th (1)
end
end

Solution

  • When you access an item in a HASH_TABLE it's possible that the item is not present. Therefore the signature of this feature is

    item (k: K): detachable G
    

    and it returns Void (or a default value for an expanded type) if the item is not found. So, when you try to use an item from HASH_TABLE, it should be checked whether it is attached or not. This can be achieved by replacing:

    table.at (1).go_i_th (1)
    

    with:

    if attached table.at (1) as la_element then
      la_element.go_i_th (1)
    end