Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference all the arguments in Julia

Tags:

julia

Is it possible to capture all the arguments and pass it to another function?

To make code like that shorter:

function send_binary(;
  binary_hash::String,
  binary::String
)::Any
  post_json(
    "http://localhost:$(port)/v1/binaries",
    json((binary_hash=binary_hash, binary=binary))
  )
end

(theoretical) Shorter version:

function send_binary(;
  binary_hash::String,
  binary::String
)::Any
  post_json("http://localhost:$(port)/v1/binaries", json(arguments))
end
like image 922
Alex Craft Avatar asked Apr 25 '26 17:04

Alex Craft


1 Answers

The splat operator captures arguments in function definitions and interpolates arguments in function calls:

julia> bar(; a=0, b=0) = a, b
bar (generic function with 1 method)

julia> foo(; kwargs...) = bar(; kwargs...)
foo (generic function with 1 method)

julia> foo(; a=1, b=2)
(1, 2)

julia> foo()
(0, 0)

julia> foo(; b=1)
(0, 1)

Your example can be written as:

function send_binary(; kwargs...)
  return post_json("http://localhost:$(port)/v1/binaries", json(; kwargs....))
end
like image 83
David Varela Avatar answered Apr 27 '26 10:04

David Varela