Why can I access the attribute of a specific struct when it's stored in a collection of abstract types?

Viewed 48
abstract type Elf end 

struct LightElf <: Elf
    name::String 
    life::Int32
end 

struct DarkElf <: Elf
    name::String
    life::Int32
    # This attribute is only in DarkElf.
    enchantment::Int32
end

amber = LightElf("Amber",100)
charles = DarkElf("Charles",20,45)

elves = Elf[]
push!(elves,amber,charles)
charles = DarkElf("Charles",20,45)
println(elves[2].enchantment)

> 45

Why can I access the enchantment field from charles when it's being stored in an array of abstract Elf objects?

In a language like C# or Java, a parent would not know about any attributes specific to that sub class. Obviously, we don't have abstract classes, so we don't know what attributes will make a generic Elf. I guess you could ask, how does Julia know about the attributes that are in a struct?

1 Answers

The answer here is that Julia is a fundamentally dynamic language, while languages like C# and Java are fundamentally static. In Julia (and most dynamic languages) variables don't have a type. Objects do. When you take elves[2] in a static language, you get a variable of type Elf. When you do it is Julia, you get a DarkElf.

Related