Thursday 7 April 2016

Julia: Create sub types

Two categories of types available in Julia.
a.   Concrete types
b.   Abstract types

Concrete types
You can create concrete types using the keyword ‘type’. You can instantiate concrete types.

julia> type Employee
                  firstName::ASCIIString
                  lastName::ASCIIString
                  id::Int64
              end

julia> 

julia> emp1=Employee("PTR", "Nayan", 1)
Employee("PTR","Nayan",1)

When a type is applied like a function it is called a constructor. Employee("PTR", "Nayan", 1) is a constructor for the type Employee. By default, Julia creates a constructor for user defined types.

Abstract types
You can create abstract types using the keyword ‘abstract’. You can’t create an object for abstract types. Abstract types are final by default, so you can’t create subtypes to an abstract type.

julia> abstract Student

julia> stud1=Student()
ERROR: MethodError: `convert` has no method matching convert(::Type{Student})
This may have arisen from a call to the constructor Student(...),
since type constructors fall back to convert methods.
Closest candidates are:
  convert{T}(::Type{T}, ::T)
  call{T}(::Type{T}, ::Any)
 in call at essentials.jl:57


Creating subtypes
By using <: (is a subtype of) operator, you can create a sub type for an abstract type.

For example,

julia> abstract Employee

julia> type permEmployee <: Employee
           firstName::ASCIIString
           lastName::ASCIIString
           id::Int64
       end

julia> type tempEmployee <: Employee
           firstName::ASCIIString
           lastName::ASCIIString
           id::Int64
           noticePeroid::Int8
       end

julia> emp1 = permEmployee("Hari", "Krishna", 1)
permEmployee("Hari","Krishna",1)

julia> emp2 = tempEmployee("Hari", "Krishna", 1, 30)
tempEmployee("Hari","Krishna",1,30)

You cant create a sub type for a concrete type.

julia> type SeniorEmployee <: tempEmployee
           name::ASCIIString
       end
ERROR: invalid subtyping in definition of SeniorEmployee


You can use the operator <: in expressions. It returns true when its left operand is a subtype of its right operand.

julia> tempEmployee <: Employee
true

julia> permEmployee <: Employee
true

julia> Employee <: tempEmployee
false

julia> Integer <: Number
true

julia> Integer <: AbstractFloat
false



Previous                                                 Next                                                 Home

No comments:

Post a Comment