liveBook · Manning

Type object

As explained in Julia as a Second Language

A type object is a Julia value representing a type and capable of being passed, stored, or operated on like other values.

A type object is a Julia value that represents a type. Because types are first-class objects, you can pass them to functions, store them, and use them to control operations such as conversion, parsing, and promotion. The type of Int64 is Type{Int64}; the type of Float64 is Type{Float64}. section 9.2 section 9.4

Type objects become especially useful when an operation must receive a type as data:

  • Convert explicitly with T(x), such as Int8(4.0), or with convert(T, x). Julia also uses convert for several implicit assignments and typed return values. section 9.2
  • Parse text by supplying the desired numeric type, as in parse(UInt8, "42") or parse(Float64, "0.42"). section 11.2.2
  • Define promotion rules with type-object arguments so values such as Radian and DMS can share generic arithmetic methods. section 9.3.7

Inspecting and using a type object

The REPL distinguishes an ordinary value from the type object that describes it: 3 isa Int64 returns true, while Int64 isa Type{Int64} also returns true. A type object can then guide an operation: parse(Int, "101", base=2) returns 5, and convert(Float64, 5) returns 5.0. This makes the target representation an explicit, passable value rather than a hard-coded assumption inside each operation. section 9.2 section 11.2.2

julia> 3 isa Int64             #1
true
 
julia> Int64 isa Type{Int64}   #2
true
 
julia> "hi" isa String
true
 
julia> String isa Type{String}
true
 
julia> Int64 isa Type{String}  #3
 false

Compare ordinary values with type objects using isa and Type{T}. section 9.2

Listing 9.12 Defining type promotion of Radian and DMS
import Base: promote_rule

promote_rule(::Type{Radian}, ::Type{DMS}) = Radian

See type objects used as dispatch-only arguments when registering a custom promotion rule. section 9.3.7

How Julia as a Second Language covers it

How deep it goes
Explains first-class behavior and Type{T}, then defers the more complex parametric-type topic.
Examples
Demonstrates constructors, convert, parse, isa checks, typed fields, typed returns, and custom promotion rules.
What you can do after
Apply type objects via constructors, parse, convert, and promote_rule to select representations and integrate custom numeric types.
How it connects
Connects type objects to conversion, multiple dispatch, generic functions, and type promotion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.