LoginSignup
22
19

More than 5 years have passed since last update.

alias, require, importの違いを理解してみる

Posted at

英語が読める方はこちらを参照のほど
elixir - alias, require and import

alias

モジュールに別名を割り当てることができる。

ex.

example.ex
defmodule Math do
  # Math.ListモジュールをListという名称に置き換え
  alias Math.List, as: List

  List.flatten             #=> Math.List.flanttenをList.flanttenとして呼び出せたり
  Elixir.List.flatten      #=> Elixirの名前空間から呼び出せたり
  Elixir.Math.List.flatten #=> Elixirの名前空間からだと置き換え元のMath.Listを呼び出せたりもする
end

またasを使わない場合は、自動的に名称が割り当てられる。

ex.

example.ex
# 最後のListの部分が割り当てられる
# つまり下記はalias Math.List, as: Listと同じ
alias Math.List

aliasはレキシカルスコープなので、特定の関数内だけのエイリアスを設定できる。

ex.

example.ex
defmodule Math do
  def plus(a, b) do
    # 下記のエイリアスはplus関数の中でのみ有効
    alias Math.List
  end

  def minus(a, b) do
    # ...
  end
end

require

モジュールを利用可能にする。

ex.

iex> Integer.is_odd(3)
** (CompileError) iex:1: you must require Integer before invoking the macro Integer.is_odd/1
iex> require Integer
nil
iex> Integer.is_odd(3)
true

モジュール内のマクロを利用するにはrequireを使い、モジュールを読み込むことが必要となる。
aliasと同じくrequireもレキシカルスコープである。

import

モジュールから他のモジュールの関数やマクロにアクセスするために使用。

ex.

# Listのduplicate関数のみ呼び出せるようにしている
iex> import List, only: [duplicate: 2]
nil
iex> duplicate :ok, 3
[:ok, :ok, :ok]

また、exept:を使えば指定した以外の関数・マクロが呼び出せるようになり、
only: macroだと全てのマクロ、only: functionsだと全ての関数が呼び出せるようになります。

単純にimport Listと呼び出した場合は、Listモジュール内の関数・マクロ全てが呼び出せます。

--

以上、理解を深めるために書いてみました。

22
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19