This behavior will be superseded by field default values:
https://github.com/JuliaLang/julia/issues/10146

On Thu, 2015-07-09 at 20:19, andrew cooke <[email protected]> wrote:
> i suspect that's by accident rather than design.  it also fails on trunk 
> with the error:
>
> ERROR: syntax: "counter=0" inside type definition is reserved  
>
> andrew
>
> On Thursday, 9 July 2015 14:19:56 UTC-3, Josh Karges wrote:
>>
>> Super late to the party here.  But this is an interesting side effect of 
>> how julia handles composite types.
>>
>> If you initialize a variable inside the type definition block it won't get 
>> added as a field to the type, but it still gets stored in memory that can 
>> be accessed by any inner constructors.
>>
>> For example:
>>
>> type myTyp
>>   id
>>   counter = 0
>>   myTyp() = new(counter+=1)
>> end
>>
>> a = myTyp(); #outputs a myTyp instance with id=1
>> b = myTyp(); #outputs a myTyp instance with id=2
>> b = myTyp(); #outputs a myTyp instance with id=3...
>>
>> The behavior is similar to how class static variables behave in oo 
>> languages.
>>
>> On Saturday, December 21, 2013 at 4:37:10 AM UTC-5, Marcus wrote:
>>>
>>> I am a little confused about constructing composite types. Given the 
>>> definition
>>>
>>> type MyType
>>> x::Int
>>> y::Int = 6
>>> MyType() = new()
>>> end
>>>
>>> an instance of MyType can be created using
>>>
>>> m = MyType()
>>>
>>> At that point, m.x acts as expected --- I can assign to it, read its 
>>> value, and so forth. However, attempting to access m.y produces an error 
>>> that MyType has no field y. Based on another post, I gather that my attempt 
>>> to provide a value to m.y in this manner is not allowed If that's the case, 
>>> what exactly is the effect of "y::Int = 6" If this part of the code is 
>>> completely ignored, it would be really nice if the system let me know since 
>>> initializing fields in this way is common in many languages.
>>>
>>> Also, I gather that a workaround is to use a constructor that takes named 
>>> arguments. Is that still the recommended way? With just two fields, things 
>>> are not difficult, but if the type has 20, calling a constructor with 20 
>>> positional arguments would be difficult.
>>>
>>>
>>>

Reply via email to