Type Annotations in Julia
Last Updated :
12 Oct, 2020
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
b = 10
a = b :: Int
print (a)
|
Output:
Example 2:
Julia
c = 20.5
d = 30.4
c + d::Float64
print (c + d)
|
Output:
Example 3:
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
struct example
x :: Int
end
x = 20
print (x)
|
Output:
Example 5:
Julia
struct Person
name::String
age:: Int
end
p = Person( "Max" , 24 )
|
Output:
Example 6:
Julia
function example(x ::Float64) ::Float32
cos(Ï€ * x)
end
result = example( 1.5 )
print (result)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...