Concise call keyword arg with default by conditional

taotree
Wed, 23 Nov 2022 15:21:23 +0000
General Usage

I tried to show an example below. This might be a bit persnickety, but it seems like it would be nice to have a cleaner solution for this situation.

I have function A with a keyword argument that specifies a default value. I have an “in between” function B that receives a value and calls function A with that value. However, if that value is nothing, it should use the default value. Is there some way to code this without what seems like redundancy?

Either I have to write a conditional at the call site, or have function A have both a default value for the argument (I need that for other cases) and convert a nothing value to that default value inside the function.

function test(x; kwarg=100)
  println(x, ' ', arg2)
end

a = nothing

# How to remove the conditional so it uses default value for kwarg?
isnothing(a) ? test(17) : test(17; kwarg=a)

3 posts - 3 participants