Syntax question: initializing nested types in a constructor

121 views
Skip to first unread message

Ian Watson

unread,
May 25, 2012, 6:32:43 PM5/25/12
to juli...@googlegroups.com
Julia continues to impress me, but I have run into a (probably quite simple) syntax road block, involving nested types, and how to initialize them.

First the inner type

type Inner
  i::Int64
  Inner() = new(-1)
  Inner(c::Int64) = new(c)
end

which is about as simple as it gets. This works just fine.

Then I try to nest this type inside another type

type Outer
  o::Int64
  inner::Inner

  Outer(c1::Int64, c2::Int64) = new(c1,c2)
  Outer(c1::Int64) = new(c1, 0)
end

o = Outer(3,4)

fails with the message:

no method convert(Type{Inner},Int64)

I tried to implement such a convert function, but could not figure it out. Not sure why that would be needed, this is a constructor. Confused and stumped, I turn here for help.

I want to do two things:

Get the Inner type initialized with either an explicit number, or with it's default initializer (no argument).

In general, if you had multiple nested types, and some required arguments, and some did not, how would one pass empty initializations to the various types? What if some types required multiple arguments for their constructor?

I'm sure this is quite simple, but I have not been able to figure it out.

Thanks

Ian

Jeff Bezanson

unread,
May 25, 2012, 6:43:34 PM5/25/12
to juli...@googlegroups.com
The short answer is "new(c1, Inner(c2))".

In julia constructors are just functions; there is no magic. Also the
notions of constructing and converting are separate; a constructor
T(x) is *not* called when x needs to be converted to T. Instead
convert(T, x) is called.

When initializing objects, you can either pass explicitly constructed
objects of the right type, or nothing at all, in which case the
corresponding fields will be uninitialized and accessing them will be
an error.

Ian Watson

unread,
May 25, 2012, 9:44:24 PM5/25/12
to juli...@googlegroups.com
Perfect! Does precisely what I wanted. Not sure I could have figured that out, but the solution definitely makes sense.

Thanks!

Progress continues, my march up the learning curve continues...

Ian
Reply all
Reply to author
Forward
0 new messages