Search code examples
erlangwarningscase-statement

Exporting variable from case Warning


When developing with erlang, I sometimes use case statements like this

case Status of
    1 ->
        Variable = "Something";
    2 ->
        Variable = "Something else";
    3 ->
        Variable = {"Something very different", [1,2,3]}
end

to assign a value to a variable depending on some condition.

The problem is: if I use it after the case statement:

do_something(Variable),

I get a compilation warning:

Warning: variable 'Variable' exported from 'case'

What is the best practice in Erlang to assign values to variables depending on some conditions and avoid such warnings?


Solution

  • The idiomatic way to do this in Erlang is to assign Variable the return value of case since case is an expression that returns the last expression's value from each branch:

    Variable = case Status of
        1 -> "Something";
        2 -> "Something else";
        3 -> {"Something very different", [1,2,3]}
    end