Reputation: 14211
The code that worked in 0.3:
type foo
bar::Int = 0
end
After migrating to Julia 0.4- produces errors like
julia4 test.jl
ERROR: LoadError: syntax: "bar::Int=0" inside type definition is reserved
in include at ./boot.jl:254
in include_from_node1 at loading.jl:133
in process_options at ./client.jl:306
in _start at ./client.jl:406
What does the error mean? How to fix it in 0.4-?
NB
I understand that it is a dev version. I also did googled and consulted the manual http://julia.readthedocs.org/en/latest/manual/types/
Upvotes: 5
Views: 2958
Reputation: 336
In the more recent versions of Julia, it is common to define structs with optional/default values as:
Base.@kwdef struct Foo
bar::Int = 0
end
This let's someone init the struct with Foo(bar=10)
to override the default values, and Foo()
will have the default value of 0
. This let's you define some defaults and some necessary parameters and have a clear initialiser.
Upvotes: 0
Reputation: 7893
Inner constructors are used to enforce invariants, in this case you just need to define the method Foo()
, notice that the method Foo(bar=0)
just creates Foo()
:
julia> type Foo
bar::Int
end
julia> methods(Foo)
# 2 methods for type constructor:
[1] Foo(bar::Int64) in Main at REPL[1]:2
[2] Foo(bar) in Main at REPL[1]:2
julia> Foo() = Foo(0)
Foo
julia> methods(Foo)
# 3 methods for type constructor:
[1] Foo() in Main at REPL[3]:1
[2] Foo(bar::Int64) in Main at REPL[1]:2
[3] Foo(bar) in Main at REPL[1]:2
Now start a new session and type:
julia> struct Foo
bar::Int
end
julia> Foo(bar=0) = Foo(bar)
Foo
julia> methods(Foo)
# 3 methods for type constructor:
[1] Foo() in Main at REPL[3]:1
[2] Foo(bar::Int64) in Main at REPL[2]:2
[3] Foo(bar) in Main at REPL[3]:1
Upvotes: 4
Reputation: 14211
Ok, the thing I come up with is to use the constructor called new()
and a function (in type) with default (python/haskell-like) parameter values:
struct Foo
bar::Int
function Foo(bar=0)
new(bar)
end
end
x = Foo()
A shorter syntactical version is (thnx @ivarne)
struct Foo
bar::Int
Foo(bar=0) = new(bar)
end
Upvotes: 9
Reputation: 3783
I don't think your so called "default field values" ever worked as you expected, but in the future (0.6 ish) it might. See https://github.com/JuliaLang/julia/issues/10146
Upvotes: 3