Erlang Central

Extend Module

From ErlangCentral Wiki

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 concept: