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?
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
This warning is not activated by default. You have to turn it on with the warn_export_vars
option. For example, putting the code above into foo.erl
:
$ erlc foo.erl
(no warning there)
$ erlc +warn_export_vars foo.erl
foo.erl:14: Warning: variable 'Variable' exported from 'case' (line 6)
I happen to think that there's nothing wrong per se with setting variables like this, so I don't turn that option on. (It's possible to write easy-to-read or hard-to-read code using either convention.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With