Pony构造函数如何工作?

时间:2016-12-04 18:01:38

标签: constructor ponylang

Pony language看起来并没有像堆栈溢出那么多,但是你必须从某个地方开始...

Here's关于Pony构造函数的非常有限的信息,这并不能帮助我理解我所看到的内容。

这是一个初始计划:

class Wombat
  let name: String
  var _hunger_level: U64

  new anon() =>
    name = "Anon"
    _hunger_level = 0

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

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

actor Main
  new create(env: Env) =>

    env.out.print("Started.")

    let wombat: Wombat = Wombat("Ernie")
    let w: Wombat = createWombat()

    env.out.print("Name: "+wombat.name)
    env.out.print("Name: "+w.name)

  fun createWombat(): Wombat =>
    let w: Wombat = Wombat("Bert")
    w

让我们将“create”构造函数重命名为“named”:

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

......我看到错误:

Error:
/src/main/main.pony:22:26: couldn't find 'create' in 'Wombat'
    let wombat: Wombat = Wombat("Ernie")

...这表明所有构造函数都不是平等的。咦......?

所以,让我们撤消这种改变。

现在让我们尝试使用零参数构造函数:

    let wombat: Wombat = Wombat()
    let w: Wombat = createWombat()

......现在我明白了:

Error:
/src/main/main.pony:22:33: not enough arguments
    let wombat: Wombat = Wombat()
                            ^

它忽略了那个构造函数。

所以,让我们重命名前两个构造函数:

  new create() =>
    name = "Anon"
    _hunger_level = 0

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

......现在我明白了:

Error:
/src/main/main.pony:22:26: couldn't find 'apply' in 'Wombat'
    let wombat: Wombat = Wombat()

不知道这意味着什么。

0 个答案:

没有答案