-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
unclear behavior of statements inside type definition #9443
Comments
like (nearly) all block constructs in julia, julia> immutable UID
next_uid = 0
my_uid::Int
UID() = (uid = next_uid; next_uid += 1; new(uid))
end
julia> UID
UID
julia> UID()
UID(0)
julia> UID()
UID(1)
julia> UID()
UID(2) improved doc for this would be appreciated. it's unclear to me whether your initial example is actually a bug or just not necessarily. as it stands now, the code to the right of the |
It could potentially be quite powerful if one could do computations on/with type-parameters like in the first example. Essentially this would be staged types #8472. Example: type A{T}
if T==Int
a::Int
else
a::Float64
b::Int
end
A(x::Int) = new(x)
A(x,y) = new(x,y)
end
A(x::Int) = A{Int}(x)
A(x,y) = A{:nt}(x,y) |
Yikes. Powerful certainly, but I feel like it might be too powerful. |
Of course one realizes that type A{T<:Int}
a::Int
A(x::Int) = new(x)
end
A(x::Int) = A{Int}(x)
type A{T}
a::Float64
b::Int
A(x,y) = new(x,y)
end
A(x,y) = A{Any}(x,y) (but still, compting with types inside type-declarations would be useful, e.g. emulating triangular dispatch...) ;-) |
related: #5790 |
This does however allow what are effectively class variables, but you have to use constructors as setters. |
@elextr, interesting, you mean like this: julia> type A
fl
a=5
A(;newa=error("reset a")) = a=newa
A(x) = new(x+a)
end
julia> A(4)
A(9)
julia> A(newa=10)
10
julia> A(4)
A(14) |
Yes, that looks about the same: use one constructor to set/get the internal variable. As this is a pretty neat, if not much used feature. Probably worth conserving if we introduce default values. |
You can use a let block (inside or outside of the type block) to get this, which is probably clearer anyway. |
Sounds good: let-blocks for class/type-variables and normal assignment for default values. |
The current (v1.8.3) error messages for the original examples are quite a bit more informative now and make it clear that you cannot do this inside a type definition, so I think we can close this as completed -- but feel free to undo if you disagree!
|
For some reason, I forgot I wasn't inside a function, and I did this
After I remembered I was inside a type definition, I concluded that statements are ignored or variables don't get set. But you can do this
The error happens before "runtime" (I don't know a better name) because
(Julia Version 0.3.4-pre+47)
The text was updated successfully, but these errors were encountered: