Scala *-parameter

Let's see how we can pass an array as argument smoothly.

We are going to see an example when this syntax shine the most: nested Node creation.

Do you experience the pain of writingNode(List(Node(List(.... Not pleasant huh ?!

But never again you will have to do this now that you know about*!

Let's see how it works:

In a function, you can haveTYPE*to take all the last parameters given to the function and turn it into an array. If you place the argument of the method withTYPE*notas last argument you will get an exception*-parameter must come last.

After doing this, instead of doingfoo(List(a,b,c))you are able to dofoo(a,b,c). And inside the body of the method you can use the parameter the same as before.

But now, let's say in some part of your code you do have aListalready but you have changed the method, you want to convert theListinto a*-parameter.

The weird syntax to do this is:foo(list:_*). It means you are casting (changing the type) , with:into_which is a wildcard, so anything, in this case, the anything being the typeAof the list which should be the same as the input type of the methodA*, and finally*.

If we look at the type only we are doing this:

list      : _* List[A] : A*

If I didn't explain well, please feel free to reach out on the Discord server so we can improve the content of this article together.

Reveal more information and clues
Load Exercise