Type conversions and promotions

The convert function can also be used explicitly in the code as convert(Int64, 7.0), which returns 7.

In general, convert(Type, x) will attempt to put the x value in an instance of Type. In most cases, type(x) will also do the trick, as in Int64(7.0), returning 7.

The conversion, however, doesn't always work:

  • When precision is lost—Int64(7.01)returns an ERROR: InexactError() error message
  • When the target type is incompatible with the source value—convert(Int64, "CV") returns an ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64 error message

This last error message really shows us how multiple dispatch works; the types of the input arguments are matched against the methods ...

Get Julia 1.0 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.