An empty array as the default value for optional arguments

function foo(x::Int64, y::Array{String}=Array{String}(undef,0))
    return x + length(y)
end

When y is an optional argument, I want to assign an empty array as the default value. While the above code works, it doesn’t seem easy to read (and not pretty). Is there a more desirable way of doing this?

function foo(x::Int64, y::Array{String}=String[])
    return x + length(y)
end
3 Likes

There’s no special syntax for “empty array as default value”. You can use String[] to create an empty array though, and you don’t necessarily need the ::Array{String} (it seems that you more likely want Vector{String} at least) and you almost certainly don’t need/want the Int64.

3 Likes

Thanks. The function return value was just arbitrarily created. In fact x needs to be an integer since it will be used as an index for an array. But I guess it needs better be Integer instead of Int64. For the array part in my case, I think you are right. I don’t need to specify the type for y I guess.