Inside type definition is reserved
Asked Answered
P

4

5

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/

Prudence answered 7/7, 2015 at 23:10 Comment(0)
P
9

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
Prudence answered 7/7, 2015 at 23:32 Comment(2)
You don't want the function keyword for short declaration.Forester
Both versions work. as @irvane mentions you forgot to remove the function keyword.Elwell
E
4

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
Elwell answered 8/7, 2015 at 23:28 Comment(0)
F
3

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

Forester answered 8/7, 2015 at 5:49 Comment(0)
C
0

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.

Carton answered 21/10, 2022 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.