Initializing explicitly with a constructor
Earlier, we saw declarations that looked like this:
my_favorite_colors Color_tab_t := Color_tab_t('PURPLE', 'GREEN');my_favorite_numbers Number_t := Number_t(42, 65536);Color_tab_t( ) is the constructor function supplied by Oracle when we created the Color_tab_t collection type. This function accepts an arbitrary number of arguments, as long as each argument is of the "proper" datatype—which in this case is VARCHAR2(30), because our original type definition statement was the following:
CREATE TYPE Color_tab_t AS TABLE OF VARCHAR2(30);At initialization, Oracle allocates to the variable an amount of memory necessary to hold the values you supply as arguments. Initialization both creates and populates the "slots" for the elements.
So, if I want to fix the earlier invalid example, I can simply initialize the variable:
DECLARE cool_colors Color_tab_t := Color_tab_t('VIOLET'); -- initializeBEGIN IF cool_colors(1) IS NULL THEN -- This is OK now!What do you suppose Oracle does with the following initialization?
This is a way of creating an empty collection. "Empty" is a kind of enigmatic state in which the collection is not atomically null but still has no data. Whenever you create such an empty collection, you'll need to "extend" the collection variable later when you want to put elements into it. (See the discussion of the EXTEND method earlier in this chapter.)
Initializing implicitly during direct assignment
You can copy the entire contents of one collection to another as long as both are built from the exact same datatype. When you do so, initialization comes along "for free."
Here's an example illustrating the implicit initialization that occurs when we assign wedding_colors to be the value of earth_colors.
DECLARE earth_colors Color_tab_t := Color_tab_t('BRICK', 'RUST', 'DIRT'); wedding_colors Color_tab_t;BEGIN wedding_colors := earth_colors; wedding_colors(3) := 'CANVAS';END;This code initializes wedding_colors and creates three elements that match those in earth_colors. These are independent variables rather than pointers to identical values; changing the third element of wedding_colors to CANVAS does not have any effect on the third element of earth_colors.
Note that assignment is not possible when datatypes are merely "type-compatible." Even if you have created two different types with the exact same definition, the fact that they have different names makes them different types.