I have an object type like below:
CREATE OR REPLACE TYPE MYOBJ AS OBJECT( Att VARCHAR2(200) );
I wish to have some constants attributes there. How should I program it? I mean I wish to have something like:
Att CONSTANT VARCHAR2(200) := 'Something'
Can I do it in spec? Or in constructor? Is it possible at all?
CodePudding user response:
You cannot have a CONSTANT
attribute of an object.
There are two alternate methods you can take:
- initialise a non-constant value in the constructor (and never change it); or
- create a static function:
CREATE OR REPLACE TYPE MYOBJ AS OBJECT(
Att VARCHAR2(200),
CONSTRUCTOR FUNCTION myobj RETURN SELF AS RESULT,
STATIC FUNCTION const_value RETURN VARCHAR2
);
CREATE OR REPLACE TYPE BODY MYOBJ AS
CONSTRUCTOR FUNCTION myobj RETURN SELF AS RESULT
IS
BEGIN
SELF.att := 'ABC';
RETURN;
END;
STATIC FUNCTION const_value RETURN VARCHAR2
IS
BEGIN
RETURN 'ABC';
END;
END;
/
Then:
SELECT MYOBJ().ATT FROM DUAL;
Creates an instance of the object, initialises the att
attribute in the constructor and then returns it. However, the value is not a constant so it is possible to modify it (but if you never change it then it will be effectively constant).
Or you can call the static function:
SELECT MYOBJ.const_value() FROM DUAL;
Which will be constant but it is not an attribute of the object.
db<>fiddle here