exsnake
exsnake

Reputation: 1823

Array inside a type in julia

I'm trying to make a type with an array inside but having trouble to do it.

This is my code:

type Gradient
    color::GrandientPoint
    Gradient(color=[]) = new(color)
    function Gradient(rgb::RGB)
        push!(color,GrandientPoint(rgb,0))
    end
end

I'm getting this error

ERROR: UndefVarError: color not defined

What am I doing wrong?

Upvotes: 3

Views: 102

Answers (1)

Chris Rackauckas
Chris Rackauckas

Reputation: 19132

function Gradient(rgb::RGB)
    push!(color,GrandientPoint(rgb,0))
end

You never made color here, so you can't push! into color since it doesn't exist. In fact, you don't need to. To define a type, you just call new with the values for it:

function Gradient(rgb::RGB)
    new(GrandientPoint(rgb,0))
end

that makes a Gradient where the first field gets the value GrandientPoint(rgb,0), and returns it.


If you wanted an array, then your type would be

type Gradient
    color::Vector{GrandientPoint}
end

not just a GraidentPoint. Now you can make that vector by using its constructor. Types have a sensible constructor from their type's name. So to make a Vector{GrandientPoint}, you just do

Vector{GraidentPoint}()

and you can push stuff into there. The full code with the constructor:

type Gradient
    color::Vector{GrandientPoint}
    Gradient(color=[]) = new(Vector{GradientPoint}())
    function Gradient(rgb::RGB)
        color = Vector{GradientPoint}()
        push!(color,GrandientPoint(rgb,0))
        new(color)
    end
end

Upvotes: 8

Related Questions