René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Storing derived types in nested tables [PL/SQL]

It's possible to store derived types in nested types:
The base type:
create type base_type as object (
  name_ varchar2(30),
  not instantiable not final member function what_are_you return varchar2
) not final not instantiable;
/
The first derived type:
create type derived_type_1 under base_type (
 
  constructor function derived_type_1(n in varchar2) return self as result,

  overriding final member function what_are_you return varchar2

) final instantiable
/
create type body derived_type_1 as

  constructor function derived_type_1(n in varchar2) return self as result is
  begin
    name_ := n;
    return;
  end derived_type_1;

  overriding final member function what_are_you return varchar2 is
  begin
    return 'I am a derived type and my name is: ' || name_;
  end what_are_you;

end;
/
The second derived type:
create type derived_type_2 under base_type (
 
  constructor function derived_type_2(n in varchar2) return self as result,

  overriding final member function what_are_you return varchar2

) final instantiable
/
create type body derived_type_2 as

  constructor function derived_type_2(n in varchar2) return self as result is
  begin
    name_ := n;
    return;
  end derived_type_2;

  overriding final member function what_are_you return varchar2 is
  begin
    return 'I''m also derived, the name being: ' || name_;
  end what_are_you;

end;
/

Creating the nested type:
create type table_of_base_types as table of base_type;
/
Fill the nested type with some derived objects and then iterate over them:
set serveroutput on

declare
  tab table_of_base_types := table_of_base_types();
begin
  
  tab.extend;
  tab(tab.count) := derived_type_1(n => 'first');

  tab.extend;
  tab(tab.count) := derived_type_2(n => 'second');

  tab.extend;
  tab(tab.count) := derived_type_2(n => 'third');

  tab.extend;
  tab(tab.count) := derived_type_1(n => 'fourth');

  for i in 1 .. tab.count loop
      dbms_output.put_line(tab(i).what_are_you);
  end loop;

end;
/
I am a derived type and my name is: first
I'm also derived, the name being: second
I'm also derived, the name being: third
I am a derived type and my name is: fourth