ponylang

ponylang: call constructor method in another constructor?


ENV: ponylang 0.9.0

From ponylang tutorial

class Wombat
  let name: String
  var _hunger_level: U64

  new create(name': String) =>
    name = name'
    _hunger_level = 0

  new hungry(name': String, hunger': U64) =>
    name = name'
    _hunger_level = hunger'

tried following, compiler complains: constructor with undefined fields

  new create(name': String) =>
    hungry(name', 0)

Where to get an exact explanation?


Solution

  • A constructor call in Pony will always create a new object, there are no delegating constructors.

    new create(name': String) =>
      hungry(name', 0)
    

    In your example, the call to hungry isn't applied to the object being initialised in create, but to the new Wombat allocated.

    In Pony pseudo-code, this is what's really happening.

    new create(this: Wombat, name': String) =>
      let new_wombat = Wombat_Alloc()
      hungry(new_wombat, name', 0)