Scala:如何继承“静态插槽”? [英] Scala: how to inherit a "static slot"?

查看:100
本文介绍了Scala:如何继承“静态插槽”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在学习Scala所以这个问题对于大多数人来说可能太基本了。

Well, I'm learning Scala so this question may be too basic for most people.

在Java中我可以有一个静态槽(函数或变量)一个类,然后我也将在继承的类中使用该插槽。

In Java I can have a static slot (function or variable) in a class, and then I will have that slot in inherited classes too.

在Scala中我没有静态插槽,但我有伴随对象。但是我发现那些对象不是继承类的一部分,所以如果我有两个类 Person Student ,和Person有一个变量 all:List 的伴随对象,它返回所有人的列表,所以我可以做 Person.all ,我原本以为我也可以 Student.all ,但事实并非如此。

In Scala I don't have static slots, but I have companion objects. But I'm finding out that those objects are not part of the inherited class, so if I have two classes Person and Student, and Person has a companion object with a variable all:List that returns a list of all persons so I can do Person.all, I was expecting that I could do Student.all too, but that's not the case.

有没有办法得到我在java中得到的相同行为?

Is there any way to get the same behaviour that I would get in java?

谢谢!

推荐答案

从理论上讲,Java在这方面的行为非常被打破。从面向对象的角度来看,子类继承静态成员的事实确实没有任何意义。静态只不过是花哨的,全局的全局。继承是你在类级别看到的东西,但是静态实际上并不属于类级别(因为它们是全局的)所以继承应该不适用。事实上它在Java中是令人不安的。

Theoretically speaking, Java's behavior in this respect is very broken. The fact that subclasses inherit static members really doesn't make any sense from an object-oriented point of view. Statics are really nothing more than fancy, scoped globals. Inheritance is something you see at the class level, but statics really aren't at the class level (since they're global) so inheritance shouldn't apply. The fact that it does in Java is...disturbing.

Scala确实走在了这个部门的高路上;我们应该感激的事情。正如另一个答案中所提到的,定义继承静态的正确方法是将继承的成员提取到特征中:

Scala has really taken the high road in this department; something for which we should all be grateful. As mentioned in another answer, the correct way to define "inherited" statics is to extract the inherited members out into a trait:

trait Inherited {
  def foo() { ... }
  def bar(i: Int) = ...
}

class Person {
  ...
}

object Person extends Inherited

class Student extends Person {
  ...
}

object Student extends Inherited

它可能看起来比Java更冗长,但请相信我我说结果语义不那么令人惊讶。

It may seem needlessly more verbose than Java, but trust me when I say that the semantics are a lot less surprising as a result.

这篇关于Scala:如何继承“静态插槽”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆