Julia is a dynamically typed language i.e. the type of the variable need not be declared in the program statically. Along with this, it also provides a technique to comment on the type of variable to the Just-in-Time (JIT) compiler at the runtime. Moreover, Julia supports both dynamic as well as static typing. This distinctive feature of Julia differentiates it from the other programming languages.
Type Annotations
Type-annotating variables in Julia can be done using the :: operator. This operator confirms that the value on the left is the same type as the value on the right.
Syntax:
<expr>::<type>
where,
expr: It can be an expression for computing a value or an assignment statement for a variable or an declaration of a variable.
type: It is the data type of the variable being used in the program.
Julia type annotations can be used for two types of expressions:
Type Assert: It is an expression that is used for computing a certain value of a variable.
Example 1 :
# Julia program to illustrate Type Assertion b = 10
# assures at runtime that 'b' will be an integer a = b :: Int print (a)
|
Output:
Example 2:
# Julia program to illustrate Type Assertion c = 20.5
d = 30.4
# assures at runtime that 'c+d' will be a float64 c + d::Float64
print (c + d)
|
Output:
Example 3:
# Julia program to illustrate Type Assertion c = 10.5
# assures at runtime that 'c+c' will be an integer c + c:: Int
|
Output:
ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64 Stacktrace: [1] top-level scope at REPL[2]:1
Variable Type Declaration:
- These are left-hand sides of assignments or declarations of local variables.
- It also covers type fields of a struct and named tuples.
- Function arguments and return type can also be type-annotated.
Example 4:
# Julia program for variable type declaration struct example # this field will always contain only integer values
x :: Int end x = 20
print (x)
|
Output:
Example 5:
# Julia program for variable type declaration struct Person # this field will always contain only string values
name::String
# this field will always contain only integer values
age:: Int end p = Person( "Max" , 24 )
|
Output:
Example 6:
# Function accepting Float64 value # and returning a Float32 value function example(x ::Float64) ::Float32 cos(π * x)
end # calling the function result = example( 1.5 )
# print result print (result)
|
Output: