E.g. is there something like this:
O = widget:new(),
O:whirl()
I seem to recall seeing some code like this (maybe I was imagining it), but I haven't seen it in the tutorials that I've read. From what I've seen, the closest thing is this:
O = widget:new(),
widget:whirl(O)
That's not too bad, but not having to repeat widget:
in the second expression would be nice.
This is syntax for parametrized modules which was removed from Erlang in R16 (2012).
No, Erlang does not have methods. Erlang has processes, not objects, and you communicate with them by messaging them, not calling methods on them. That's it. That's all there is to it.
The closest thing to new
in Erlang that means what it means in Java or C++ is spawn
. (The parameterized module discussion touches on something very different from what you would expect coming from a C++ type language where new
reserves memory, calls a constructor, etc.)
There are actually two aspects to this: data objects (like a dict or list or something) and processes (things you create with spawn
).
Within a function definition you might see something like
SomeDict = dict:new(),
or
OtherDict = dict:from_list(KV_List)
This does indeed create something, but its not an "object" in the Java or C++ sense, it is an "object" in the (older) sense of the term that it is a named reference to something in memory. And indeed you interact with it the same way you demonstrated above:
D = dict:new(),
ok = some_operation(D),
where some_operation/1
might be anything, whether it is dict:foo()
or something else. The part before the colon is a module identifier, telling the runtime what namespace that function you're calling exists in -- nothing more.
The other thing, spawn
, is much more like new
in C++, where you want to create a complete thing that is alive and has arms and legs -- a noun that can do verby things:
Pid = spawn(Mod, Fun, Args),
Pid ! {some, message},
Most of the time you only see the erlang:send/2
function (also written as the infix !
operator) in prototype or non-OTP code. Usually this is hidden from you by interface functions that abstract away the fact that you are sending async messages all the time to communicate with your processes.
For some more in-depth explanation, I recommend reading Learn You Some Erlang -- the author explains this and other basic concepts in some depth.
Whatever you do, do not fall into the simpleton's trap of thinking Erlang is Java. That is just a great way to trip over your own preconceptions and get frustrated. This is probably the #1 beginner mistake I see people make...