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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.