Tuesday, 5 April 2016

Julia: Type conversion for user defined types


By using convert function, you can convert user defined types to other types.

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

julia> emp1 = Employee("Hari Krishna", "Gurram", 123)
Employee("Hari Krishna","Gurram",123)

julia> convert(::Type{Int64}, emp::Employee) = emp.id
convert (generic function with 2 methods)

julia> convert(::Type{ASCIIString}, emp::Employee) = emp.firstName
convert (generic function with 3 methods)

julia> convert(Int64, emp1)
123

julia> convert(ASCIIString, emp1)
"Hari Krishna"

convert(::Type{Int64}, emp::Employee) = emp.id
Above function convert Employee instance to integer

convert(::Type{ASCIIString}, emp::Employee) = emp.firstName
Above function convert Employee instance to ASCIIString.



Previous                                                 Next                                                 Home

No comments:

Post a Comment