Accepting variable numbers of arguments

Sometimes, it is more convenient if the function can just accept any number of arguments. In this case, we can add three dots ... to a function argument and Julia will automatically roll up all passed arguments into a single variable. This feature is known as slurping.

Here is an example:

# Shoot any number of targets
function shoot(from::Widget, targets::Widget...)
println("Type of targets: ", typeof(targets))
for target in targets
println(from.name, " --> ", target.name)
end
end

In the shoot function, we first print the type of the targets variable and then print every shot that was fired. Let's set up the game pieces first:

spaceship = Widget("Spaceship", Position(0, 0), Size(30,30))
target1 = asteroids[1]
target2 = asteroids[2]
target3 = asteroids[3]

Now we can start shooting! Let's first call the shoot function by passing a single target and then do that again by passing three targets:

It turns out that the arguments are just combined as a tuple and bound to a single targets variable. In this case, we just iterate the tuple and perform an action on each of them.

Slurping is a fantastic way to combine function arguments and handle them all together. This makes it possible to call the function with any number of arguments.

Next, we will learn about a similar feature called splatting, which essentially performs the opposite function of slurping.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.154.103