In terms of type stability ( http://docs.julialang.org/en/release-0.4/manual/performance-tips/#avoid-changing-the-type-of-a-variable ), the latter is better:
f1(x::Int, y::Union{Void,Dict}) = y==nothing ? Dict() : y @code_warntype f1(42, nothing) # shows ...end::UNION{DICT{ANY,ANY},VOID}; type unstable! @code_warntype f1(42, Dict()) # shows ...end::Dict{Any,Any} compare this to f2(x::Int, y::Dict=Dict()) = y @code_warntype f2(42) # shows ...end::Dict{Any,Any}; type stable @code_warntype f2(42, Dict()) # shows ... end::Dict{Any,Any} Whether you write f(x::Int, y=Dict()) or f(x::Int, y::Dict=Dict()) is a separate issue, about which Tamas and Tom made good suggestions. On Thursday, May 5, 2016 at 1:58:42 PM UTC+2, Tom Breloff wrote: > > Just to extend Tamas's note... Another reason you may add the type > annotation is to ensure your code errors when you pass it types that are > not valid (but may compile and dispatch without issue). > > On Thursday, May 5, 2016, Tamas Papp <tkp...@gmail.com <javascript:>> > wrote: > >> Hard to say without the context, but since in this case the only purpose >> of a `nothing` seems to be to initialize with a default value, I would >> go with y=Dict(), which does it directly. >> >> (Note that unless you are dispatching on them, your type declarations >> are probably unnecessary, they won't make your code faster.) >> >> On Thu, May 05 2016, FANG Colin wrote: >> >> > For example, >> > >> > function f(x::Int; y::Union{Void, Dict}) >> > z = y == nothing ? Dict() : y >> > ... >> > end >> > >> > >> > Or >> > >> > function f(x::Int; y::Dict=Dict()) >> > ... >> > end >> > >> > Which one should I use? >> >