Erlang Central

Difference between revisions of "Extend Module"

From ErlangCentral Wiki

(New page: Erlang provides the ability to do simple module inheritance using the 'extend' module attribute. This was originally proposed by Richard Carlsson in [http://www.erlang.se/euc/07/papers/170...)
 
Line 5: Line 5:
 
parent.erl:
 
parent.erl:
 
  -module(parent).
 
  -module(parent).
  -export([print_name/0]).
+
  -export([print_name/0,print_name2/0]).
 
   
 
   
 
  print_name() ->
 
  print_name() ->
 +
    io:format("~p~n", [?MODULE]).
 +
 +
print_name2() ->
 
     io:format("~p~n", [?MODULE]).
 
     io:format("~p~n", [?MODULE]).
  
 
child.erl:
 
child.erl:
 
  -module(child).
 
  -module(child).
  -extend(parent).
+
  -extends(parent).
 +
-export([print_name2/0]).
 
   
 
   
 +
print_name2() ->
 +
    io:format("~p~n", [?MODULE]).
 +
 
Shell:
 
Shell:
 
  44> c(parent).
 
  44> c(parent).

Revision as of 12:56, 12 April 2010

Erlang provides the ability to do simple module inheritance using the 'extend' module attribute. This was originally proposed by Richard Carlsson in 'Inheritance in Erlang'.

It works as follows.

parent.erl:

-module(parent).
-export([print_name/0,print_name2/0]).

print_name() ->
   io:format("~p~n", [?MODULE]).

print_name2() ->
   io:format("~p~n", [?MODULE]).

child.erl:

-module(child).
-extends(parent).
-export([print_name2/0]).

print_name2() ->
   io:format("~p~n", [?MODULE]).

Shell:

44> c(parent).
{ok, parent}
45> c(child).
{ok, child}
46> parent:module_info().
[{exports,[{print_name2,0},
           {print_name,0},
           {module_info,0},
           {module_info,1}]},
 {imports,[]},
 {attributes,[{vsn,[170232170699999308993405016497184790000]}]},
 {compile,[{options,[]},
           {version,"4.6.4"},
           {time,{2010,2,21,20,15,48}},
           {source,"/home/bile/code/erlang/test/parent.erl"}]}]
47> child:module_info().
[{exports,[{print_name2,0},{module_info,0},{module_info,1}]},
 {imports,[]},
 {attributes,[{vsn,[26441608909026232271209326103084341806]},
              {extends,[parent]}]},
 {compile,[{options,[]},
           {version,"4.6.4"},
           {time,{2010,2,21,20,18,33}},
           {source,"/home/bile/code/erlang/test/child.erl"}]}]
48> parent:print_name().
parent
ok
49> parent:print_name2().
parent
ok
50> child:print_name().  
parent
ok
51> child:print_name2().
child
ok

Related concepts: