0
votes

In Elixir instead of writing something like:

case getUser(id) do
  %User{status: "pending"} -> something()
  %User{status: "available"} -> something()
  _ -> something_else()
end

I simplified it into:

case getUser(id) do
  %User{status: "pending" | "available"} -> something()
  _ -> something_else()
end

But got an error:

cannot find or invoke local |/2 inside match. Only macros can be invoked in a match and they must be defined before their invocation. Called as: "pending" | "available"

is there a better way of doing this? I don't want to write the same function twice.

1
Please amend your code to use curly brackets for structs. What is posted would not even compile. - Aleksei Matiushkin
Thank you, I’ve edited - it was an error while typing. - Olufemi Ayodele

1 Answers

3
votes
case getUser(id) do
  %User{status: status} when status in ["pending", "available"] -> something()
  _ -> something_else()
end

The when .. in is a Guard and is mentioned briefly on the case, cond, and if page.