Book Image

Getting Started with Julia

By : Ivo Balbaert
Book Image

Getting Started with Julia

By: Ivo Balbaert

Overview of this book

Table of Contents (19 chapters)
Getting Started with Julia
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
The Rationale for Julia
Index

Types and collections – inner constructors


Here is another type with only default constructors:

# see the code in Chapter 6\inner_constructors.jl
type Person
    firstname::String
    lastname::String
    sex::Char
    age::Float64
    children::Array{String, 1}
end
p1 = Person("Alan", "Bates", 'M', 45.5, ["Jeff", "Stephan"])

This example demonstrates that an object can contain collections such as arrays or dictionaries. Custom types can also be stored in a collection, just like built-in types, for example:

people = Person[]

This returns 0-element Array{Person,1}.

push!(people, p1)
push!(people, Person("Julia", "Smith", 'F', 27, ["Viral"]))

The show(people) function now returns the following output:

[Person("Alan","Bates",'M',45.5,String["Jeff","Stephan"]),
 Person("Julia","Smith",'F',27.0,String["Viral"])]

Now, we can define a function fullname on type Person. You notice that the definition stays outside the type's code:

fullname(p::Person) = "$(p.firstname) $(p.lastname)"  

Or, slightly more performant...