如何在Julia中使用Null argumnet创建构造函数

时间:2016-05-20 19:20:47

标签: julia

我想用参数类型Family创建类型Family,但我想用Null参数创建可能性

type Family
    name:: AbstracDtring
    people:: Int
    dad:: Family
    mom:: Family

Family(name:: AbstractString, people::Int ) = new (name, people , NULL, NULL)


end

我可以做这个事情我想创建“对象”引用另一个对象或没有引用

2 个答案:

答案 0 :(得分:4)

您可以使用较少的参数调用new

type Family
    name::AbstractString
    people::Int
    dad::Family
    mom::Family

    Family(name::AbstractString, people::Int) = new(name, people)
end

您可以构建实例,但在分配.dad.mom字段之前,访问它们会导致错误:

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

您可以使用isdefined功能检查字段是否已定义:

julia> isdefined(fam, :dad)
true

julia> isdefined(fam, :mom)
false

Nullable方法也有效,但重量稍轻一些。

答案 1 :(得分:3)

使用Nullablehttp://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