Parametric constructor, promotion and splatting (...)

Hi there,

I am reading the page ParametricConstructors of the manual, where a struct Point is defined as:

struct Point{T<:Real}
           Point{T}(x,y) where {T<:Real} = new(x,y)

and then the following constructor is presented:

Point(x::Real, y::Real) = Point(promote(x,y)...)

I am particularly intrigued with the use of the splatting operator (…) rigtht after the promote(x,y) call. In this very same example it seems unnecessary, since there are exactly two arguments for Point in the left-hand side as well for promote in the right-hand side. Is this really the case here? If so, I wonder about a specific example, in another context, where the use of the splatting operator would make sense or, perhaps, be unavoidable.


1 Like

promote(x, y) returns a tuple, while the Point constructor excepts two separate arguments. Consider if instead of a Point, I tried to promote two things and place them in a vector:

julia> promote(1.0, 2)
(1.0, 2.0)

julia> [promote(1.0, 2)]
1-element Array{Tuple{Float64,Float64},1}:
 (1.0, 2.0)

julia> [promote(1.0, 2)...]
2-element Array{Float64,1}:

Splatting “unpacks” the iterator, making the call treat each element as separate argument.

This is precisely such a case :wink: