A Tour of Morfa

Variadic functions

A variadic function must have the last argument of a dynamic array type and ... at the end of the list of parameters.

func sum(first: int, rest: int[]...)
{
    var s = first;
    for (arg in rest)
        s += arg;
    return s;
}

unittest
{
    assert (sum(1, 2, 3) == 1 + 2 + 3);
    assert (sum(7) == 7); 
    // sum() would be invalid
}

When a variadic function is a part of an overload set, it is considered less specific than non-variadic variants:

// A special super-fast case for adding just two integers,
// will be selected when calling sum(a,b).
func sum(first: int, second: int)
{
    return first + second; 
}

Templated variadic functions

In the above examples all arguments had to have the same type. A function which takes any number of arguments of different types may be defined as a variadic function template. For more in-depth description of template programming refer to Templates section.

import morfa.base;

public template <Args...>
func whatArgs(args: Args): void
{
    for (i in StaticRange<Args.length>)
    {
        static if (i > 0)
            print(" ");
        static if (Is<Args[i], text>)
            print("Got text!");
        else static if (IsNumberType<Args[i]>)
            print("Got some number!");
        else
            print("And what is this?!");
    }
    println();
}

unittest
{
    whatArgs("text", 5, 5.6, new Object);
}