Handling nil in case

Hello. I’m thinking the way to handle nil in case.

|> case do
    x when not is_nil(x) -> 
      ...
      {:ok, "xxxxxx"}
    nil ->
      ...
      {:error, "xxxxxxxx"}
end
|> case do
    nil -> 
      ...
      {:error, "xxxxxxxx"}
    topic ->
      ...
      {:ok, "xxxxxxxx"}
end

When I handle nil in case, I write codes in a latter way. What do you think of that?

You can also do like this, if topic is some kind of struct.

|> case do
  %Topic{} = topic -> ...
  nil -> ...
end
1 Like

Oops, I made a mistake. I should have changed topic to x :sweat_smile:
topic in the latter way is binary, so I only thought out the 2 ways.
Thank you!

About piping into case a good mention was in Good and Bad Elixir post. May be you should consider to match it to some variable? Especially with nil result possibility, you could rewrite it to if some_result, do: something, else: another

1 Like

In case, I always go from most concrete to least concrete, like so:

case something do
  nil -> "nil"
  :a -> "the atom :a"
  text when is_binary(text) -> "text"
  list when is_list(list) -> "list"
  other -> raise(ArgumentError, "unexpected value: #{inspect(other)}"
end
4 Likes

I’d like to use value of x in the process, so I chose case.
Do you give me an idea if the value is used in the pipelines?

At least that is said in the article :slight_smile: If you think it makes sence, yeah, you may assign intermediate result into variable and use it in case explicit. But it’s hard to tell without upstream code.

1 Like