Handle Param wihich may/may not have key

I am getting params that may/may not have the key. For example here is my params

params: %{"job_opening_id" => job_opening_id, "stage_id" => stage_id}

Sometimes, my params only contain job_opening_id and sometimes both. How can make pattern matching that accepts both types of params?

You can’t. Pattern matches are meant to ensure the given data fulfills the pattern given. If you have optional data either use multiple patterns/functions or extract the data in the functions body using e.g. Map.get.


Aren`t they two different methods matching any of the cases?

1 Like

You can define a function that matches a map having both keys, and afterwards one that matches a partial map and calls the previous after putting defaults:

def foo(%{"param1" => param1, "param2" => param2}) do

def foo(params) when is_map(params) do
  |> Map.put_new("param1", default_param1)
  # as many as needed
  |> foo()

This sounds like a quite complex way of doing params = Map.merge(defaults, params).


If you don’t want to use another function head then do something like this:

def foo(%{"job_opening_id" => job_opening_id} = params) do
  # stage_id will be either nil or have a value
  stage_id = params["stage_id"]


You can test for nil via if or case and do something depending on weather stage_id has a value.

1 Like