是否可以在 Scala 中进行基于原型的编程?

发布于 2024-10-19 11:34:40 字数 30 浏览 1 评论 0原文

是否可以在 Scala 中进行基于原型的编程?

Is it possible to do prototype-based programming in Scala?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小巷里的女流氓 2024-10-26 11:34:40

我不同意 Easy Angel 的观点...Scala 对象不需要类(它们仍然都有一个类型...但这不一样)。 不需要

val martin = new { 
  val name = "Martin"
  val surname = "Ring"
  def age = Calendar.getInstance.get(Calendar.YEAR) - 1986
}

由于结构类型,您可以为这些对象编写函数:

def printPerson(person: { def name: String; def age: Int }) = 
  println("%s (%d)".format(person.name, person.age))

您可以调用 printPerson(martin) ,它会打印出 Martin (25)

所以 如果你真的想要的话,需要类或特征。

然而,该语言仍然不支持基于原型的编程,因为它(恕我直言)不可能克隆和扩展具有匿名类型的对象。我想你可以编写函数来做到这一点......但它们需要大量使用反射,因此没有本机语言支持......

I have to disagree with Easy Angel... Scala objects do not need classes (they still all have a type... but that is not the same). Its perfectly ok to write

val martin = new { 
  val name = "Martin"
  val surname = "Ring"
  def age = Calendar.getInstance.get(Calendar.YEAR) - 1986
}

also thanks to structural typing you can write functions for these objects:

def printPerson(person: { def name: String; def age: Int }) = 
  println("%s (%d)".format(person.name, person.age))

you can call printPerson(martin) and it will print out Martin (25)

So no need for classes or traits if you really want that.

However prototype-based programming is still not supported by the language as it (imho) is not possible to clone and extend objects with anonymous type. I guess you could write functions to do that... but they would require massive use of reflection and thus there is no native lanugage support..

旧伤还要旧人安 2024-10-26 11:34:40

虽然我同意 EasyAngel 的观点,但根据您想要如何使用原型机制,您也许可以使用 Scala 机制实现类似的目标。例如,您可以定义一个可以混合到更通用的类中的特征。

在某些方面,这比原型对象生成更强大,因为您可以混合和匹配各种潜在相关的特征。您还可以从目标子类中自定义和扩展它们。

进一步澄清您的问题将使您得到更有针对性的答案。

While I agree with EasyAngel, depending on how you want to use a prototype mechanism, you may be able to achieve similar goals with Scala mechanisms. For example, you can define a trait that can be mixedin to a more generic class.

In some ways this is more powerful than prototype object generation, because you can mix and match a variety of potentially relevant traits. You can also customize and extend them from within a target subclass.

Further clarifying your question will allow more focused answers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文