No error for duplicate aliases

Elixir 1.7.
Why isn’t there a simple error message when I try to define a duplicate alias?

defmodule Mytest do
  alias MyApp.Schema.Channel
  alias MyApp.Channel

  def test do
    Channel.list()
  end
end

I added code to an existing file that already had the Schema for Channel and I didn’t notice it. But rather than failing to compile with a nice message like “Duplicate Alias detected”, or something, the compile of the whole app failed because Phoenix couldn’t generate my MyApp.Router.Helpers file. Clearly not Phoenix’s fault. The file above compiles with no warning. Why? Is there any circumstance in which it is valid and useful to have two aliases that are the same? How would one use both of them?

To answer your last question:

  alias MyApp.Schema.Channel, as: SchemaChannel
  alias MyApp.Channel

alias applies to code below it in the file, so it’s possible (although very odd) to re-alias things:

defmodule Foo.Bar do
  def call_thing(), do: IO.inspect(__MODULE__)
end

defmodule Baz.Bar do
  def call_thing(), do: IO.inspect(__MODULE__)
end

defmodule AliasTest do
  def test do
    alias Foo.Bar
    Bar.call_thing()
    alias Baz.Bar
    Bar.call_thing()
  end
end

AliasTest.test()
# Foo.Bar
# Baz.Bar
1 Like

Well, it would be nice if it would at least give a warning in the case that you have:

alias Schema.Channel
alias App.Channel
  def test do
    Channel.myfun()
  end

that the second alias obscures the first without it being used. Essentially the first alias is now unused and should cause a warning. In your example the Foo.Bar does get used and shouldn’t generate a warning, but in mine the Schema.Channel isn’t used and should generate the same warning as if I deleted the call to myfun.

Oh, dear. Changing myfun to a full module path to another module didn’t cause warnings about unused aliases for either of the Channels. :frowning: What condition is necessary for the unused alias to cause a warning?

1 Like