【问题标题】:How to extend a Fantom class that implements a serialisation constructor?如何扩展实现序列化构造函数的 Fantom 类?
【发布时间】:2015-12-08 10:19:58
【问题描述】:

Fantom 编程语言的一个强大功能是it-block constructor,经常用于可序列化的类中。不幸的是,我找不到足够详细的文档来做我认为应该很简单的事情:扩展一个声明这种类型的构造函数的类。到目前为止,我发现的最好的文档位于 this post,但没有显示我正在尝试做的示例。

假设我有这些课程:

class Animal {
  protected const Str name
  new make( |This| f ) { f(this) }
  override Str toStr() { "I'm an Animal and my name is $name" }
}

class Main {
  Void main() {
    a := Animal {
      name = "Flipper"
    }
    echo( a )
  }
}

到目前为止一切顺利,它打印出:“我是动物,我的名字是鳍状肢”。现在我想用这个类来扩展 Animal:

class Dog : Animal {
  override Str toStr() { "I'm an Dog and my name is $name" }
}

但是 Fantom 编译器说:

Must call super class constructor in 'make'

所以我把班级改成:

class Dog : Animal {
  new make( |This| f ) : super( this ) { f(this) }
  override Str toStr() { "I'm an Dog and my name is $name" }
}

但现在编译器抱怨:

invalid args make(|Playground::Animal->sys::Void|), not (Playground::Dog)

这是有道理的,因为我传递的是 Dog 实例,而不是 Animal,那么我应该将什么传递给超级构造函数?

【问题讨论】:

    标签: fantom


    【解决方案1】:

    在仔细考虑编译器错误后,我意识到我必须传递的只是 f:

    class Dog : Animal {
      new make( |This| f ) : super( f ) { }
      override Str toStr() { "I'm an Dog and my name is $name" }
    }
    

    我希望这对其他人有所帮助。

    【讨论】:

    • 在 Dog 的 ctor 中不需要调用 f(this),因为它已经在 Animal 的 ctor 中调用了。
    • 感谢史蒂夫指出这一点。我删除了不需要的调用。
    猜你喜欢
    • 2013-01-30
    • 2013-07-29
    • 1970-01-01
    • 2018-09-26
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2019-01-07
    相关资源
    最近更新 更多