CompileError: "invalid use of _. "_" represents a value to be ignored in a pattern and cannot be used in expressions"

Maxximiliann
Sat, 25 Dec 2021 00:04:15 +0000
Questions / Help

This case statement is perfectly functional, but it repeats code:

case foo do
  {:pass, _} = reason ->
    Logger.info(reason)

  {:ok, _, _} ->
    status = Keyword.get(opts, :status)
    some_func(status)

    Logger.info("Executing function: #{some_func} with status: #{status}")

  {:ok, :bosh} ->
    status = Keyword.get(opts, :status)
    some_func(status)

    Logger.info("Executing function: #{some_func} with status: #{status}")
end

To eliminate repetition, the following version was attempted, however it results in a CompileError: invalid use of _. "_" represents a value to be ignored in a pattern and cannot be used in expressions

case foo do
  {:pass, _} = reason ->
    Logger.info(reason)

  message
  when message == {:ok, _, _} or message == {:ok, :bosh} ->

    status = Keyword.get(opts, :status)
    some_func(status)

    Logger.info("Executing function: #{some_func} with status: #{status}")
end

What’s the best way to resolve this issue in a case statement? What alternate control flow structure, if any, would be more appropriate for this task?

11 posts - 5 participants