defmodule TrackingState do
def loop(state \\ []) do
receive do
{:push, item} -> state = [item | state]
whatever -> {:error, "#{whatever} is not a valid"}
end
IO.inspect(state)
loop(state)
end
end
The error is:
warning: the variable “state” is unsafe as it has been set inside one of: case, cond, receive, if, and, or, &&, ||. Please explicitly return the variable value instead. For example:
case integer do
1 -> atom = :one
2 -> atom = :two
end
should be written as
atom =
case integer do
1 -> :one
2 -> :two
end
Unsafe variable found at:
Desktop/junk/test.ex:8
The error is just a warning but I would like to know how to fix it.
The warning does show how to fix it. Just replace case in warning with receive from your code and you should see some similarities.
Either way you need to think what shall happen to state when you received something invalid?
Perhaps remain unchanged? Makes no sense for me but mirrors your current code:
defmodule TrackingState do
def loop(state \\ []) do
state = receive do
{:push, item} -> [item | state]
whatever ->
{:error, "#{whatever} is not a valid"}
state
end
IO.inspect(state)
loop(state)
end
end