efe icon indicating copy to clipboard operation
efe copied to clipboard

Elixir will warn when variables prefixed with underscore are used

Open eksperimental opened this issue 3 years ago • 3 comments

underscore_variable() ->
  case 1 of
    x when is_atom(x) ->
      atom;
    _Other ->
      _Other
  end.

will transpile as

  defp underscore_variable() do
    case (1) do
      :x when is_atom(:x) ->
        :atom
      _Other ->
        _Other
    end
  end

but the compiler will emit a warning:

warning: the underscored variable "_Other" is used after being set. A leading underscore indicates that the value of the variable should be ignored. If this is intended please rename the variable to remove the underscore
  out/samples/cornercases.ex:215: :cornercases.underscore_variable/0

I think the underscore should be removed

eksperimental avatar Apr 03 '21 19:04 eksperimental

The problem is that there may be a variable called Other, removing the underscore may change the meaning of the program.

marianoguerra avatar Apr 06 '21 07:04 marianoguerra

A good compromise would be to remove the underscore if there is no other variable named like that. If there is, leave it and let the user deal with the warning. Having _Other and Other and using both is bad practice anyway.

eksperimental avatar Apr 06 '21 14:04 eksperimental

I see what you mean. It is related to the other variable scope issue. It could use the name of another variable defined outside case, or the program relies on the variable after case.

eksperimental avatar Apr 06 '21 14:04 eksperimental