0

Say, I have 2 modules.

defmodule Mod1 do
  @var1 123
end


defmodule Mod1.Mod2 do
  def func1 do
    @var1 * 10 # how ????
  end
end

Is there any way to access @var1 without having to create a special function for it in Mod1?

defmodule Mod1 do
  @var1 123

  def var1_getter do    # only for Mod2
    @var1 123           # any other way???
  end
end
2
  • I advise to read more documentation and read carefully "Programming Elixir" before asking here. Commented Feb 9, 2017 at 12:26
  • 1
    @PatNowak, aaahhhhhaaaaahhhaa Commented Feb 10, 2017 at 6:11

1 Answer 1

4

Is there any way to access @var1 without having to create a special function for it in Mod1?

No, there isn't. Module attributes only exist at compile time and if you want to expose their values, you need to return it from a public function.

Also, there's nothing special about nested modules in Elixir except that the name of the parent module is a prefix of the name of its children. After compilation, they're completely separate modules that happened to be named Mod1 and Mod1.Mod2.

Sign up to request clarification or add additional context in comments.

3 Comments

It is worth mentioning that Kernel.@ is a plain old good macro that is basically a sophisticated-check-enabled alias for Module.put_attribute/3.
Elixir is far away from OOP, so nested modules are not nested classes and module attributes are far from class fields.
you can define a macro __USING__ and write all your attributes inside the macro and load them into your module like this use module_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.