Understanding numeric type conversions

Julia does not automatically perform conversion on data types for safety reasons. Every conversion must be explicitly defined by the programmer. 

To make it easier for everyone, Julia already contains conversion functions for numeric types by default. For instance, you can find this interesting piece of code from the Base package:

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

Both functions take the first argument of the Type{T} type, where T is a subtype of Number. Valid values include all standard numeric types, such as Int64, Int32, Float64, Float32, and so on.

Let's try to understand these two functions further:

  • The first function says that it's as easy as returning the argument x itself when we want to convert x from the T type and to the T type (the same type) as long as T is a subtype of Number. This can be considered a performance optimization because there is really no need to do any conversion when the target type is the same as the input.
  • The second function is a little more interesting. In order to convert x, which is a subtype of Number, to type T, which is also a subtype of Number, it just calls the constructor of the T type with x. In other words, this function can handle the conversion of any Number type to another type that is a subtype of Number.

You may wonder why we don't just use the constructor in the first place. This is because the convert function is designed to be invoked automatically for various common use cases. As you can see from what we looked at previously, this extra indirection also allows us to bypass the constructor when conversion is unnecessary.

When does convert get called? The answer is that Julia does not automatically do that, except for a few scenarios. We will explore these scenarios in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.84.112