`convert` vs constructor

Which is considered better Julia style, this:

f(a::T) where{T<:Number} = T(2)

or this:

f(a::T) where{T<:Number} = convert(T,2)

Or are they equivalent in practice?

They are often inequivalent. See the manual.

2 Likes

Sorry, I should have been more explicit in my question. I was asking for the particular case of Number types, not the more general case.

I believe this function is defined:

convert(::Type{T}, x::Number) where {T<:Number} = T(x)

which seems to imply that convert() and T() would be equivalent because convert reduces to calls to T().

Is this incorrect?

It is entirely appropriate to define a conversion method Base.convert,
to convert into a type T as a call to the constructor for the type T.
Doing so suggests that there is no special handling (outside of that which may be part of the constructor’s own internal logic) required for a correct conversion from (here, Number) to T.

For Number types, I would typically just use T(x) since it is shorter than convert(T, x) and there should be no difference in behavior.

1 Like