Reputation: 113
I want to create type Family with argument type Family but i want to create possibility with Null argument
type Family
name:: AbstracDtring
people:: Int
dad:: Family
mom:: Family
Family(name:: AbstractString, people::Int ) = new (name, people , NULL, NULL)
end
Can i do somthing with this i want create "object" with references to another object or without references
Upvotes: 3
Views: 894
Reputation: 33249
You can call new
with fewer arguments:
type Family
name::AbstractString
people::Int
dad::Family
mom::Family
Family(name::AbstractString, people::Int) = new(name, people)
end
You can construct instances but until you've assigned the .dad
and .mom
fields, accessing them will cause an error:
julia> fam = Family("Jones", 3)
Family("Jones",3,#undef,#undef)
julia> fam.dad
ERROR: UndefRefError: access to undefined reference
in eval(::Module, ::Any) at ./boot.jl:225
in macro expansion at ./REPL.jl:92 [inlined]
in (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:46
julia> fam.mom
ERROR: UndefRefError: access to undefined reference
in eval(::Module, ::Any) at ./boot.jl:225
in macro expansion at ./REPL.jl:92 [inlined]
in (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:46
julia> fam.dad = fam
Family("Jones",3,Family(#= circular reference @-1 =#),#undef)
julia> fam.mom
ERROR: UndefRefError: access to undefined reference
in eval(::Module, ::Any) at ./boot.jl:225
in macro expansion at ./REPL.jl:92 [inlined]
in (::Base.REPL.##1#2{Base.REPL.REPLBackend})() at ./event.jl:46
You can check if a field is defined or not using the isdefined
function:
julia> isdefined(fam, :dad)
true
julia> isdefined(fam, :mom)
false
The Nullable
approach works too but this is somewhat lighter weight.
Upvotes: 5
Reputation: 21717
Use Nullable
(http://docs.julialang.org/en/release-0.4/manual/types/#nullable-types-representing-missing-values)
type Family
name:: AbstractString
people:: Int
dad:: Nullable{Family}
mom:: Nullable{Family}
Family(name:: AbstractString, people::Int ) = new(name, people, Nullable{Family}(), Nullable{Family}())
end
Upvotes: 4