Julia Type Hints

Julia is a dynamically typed language, but type hints serve several purposes.


Description

To provide the interpreter/compiler a type hint, try:

julia> (1+2)::Int

This acts as a type assertion: if the annotated value is not that type, then a type error is thrown.


Function Arguments

Try:

function foo(x::Int, y::Int)
    x + y
end

Best practice is to use abstract types on function arguments, so that novel subtypes found in packages can seamlessly work.


Struct Members

By default, struct fields are typed as Any. Type hints can be applied to fields like:

julia> struct Foo
           bar
           baz::Int
           qux::Float64
       end

julia> foo = Foo("Hello, world.", 23, 1.5)
Foo("Hello, world.", 23, 1.5)

This causes values to be type cast, and potentially throw an error.

julia> Foo("Hello, world.", 23.5, 1)
ERROR: InexactError: Int64(23.5)


CategoryRicottone

Julia/TypeHints (last edited 2026-01-18 17:51:09 by DominicRicottone)