I am new to Elixir and Phoenix and trying to wrap my head around it. In the Phoenix hello app I generated I have the following line which I am trying to make sense of
scope "/", HelloWeb do
get "/", PageController, :index --- (1)
I’m a bit confused by line
(1) and specifically the
:index part. PageController is a module and
index is a function inside it, but why use the
: when referring to it and how is this even possible.
Hi @andym! There is a built in function called Kernel — Elixir v1.14.2 that lets you call a function by providing the module, the atom name of the function, and then a list of arguments:
iex(1)> IO.puts "hello"
iex(2)> apply(IO, :puts, ["hello"])
This leads to a general convention in various Elixir (and Erlang) libraries of specifying function names as atoms, and then the library can use
apply later to call the function supplied.
thanks @benwilson512, is this the same as function capturing and if not how are they different Modules and functions - The Elixir programming language
apply is related than function capture.
apply try to invoke existing function, with a given Module, Function, Argument (aka MFA) or an anonymous function and argument. function capture tries to make an anonymous function from existing function, so that anonymous function could be passed around as argument/variable and invoked at a later time. anonymous function in general is a bit more flexible compared to MFA as they don’t need to have a defined module and defined function.