Olufemi Ayodele
Olufemi Ayodele

Reputation: 407

Elixir: Pattern match with multiple map match options

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.

Upvotes: 0

Views: 831

Answers (1)

NoDisplayName
NoDisplayName

Reputation: 15736

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.

Upvotes: 3

Related Questions