【问题标题】:Scala - duplicated hierarchy for companion objectScala - 伴生对象的重复层次结构
【发布时间】:2018-10-25 21:34:25
【问题描述】:

我是 Scala 的新手,我想知道哪种方法是组织类及其伴随对象的层次结构的最佳方式。

假设我有一个要扩展的基类或接口。在 Python 中,我会做这样的事情:

class Base(object):
    def an_instance_method(self):
        return 0

    @classmethod
    def a_class_method(cls):
        return 1

    def another_instance_method(self):
        raise NotImplentedError()

    @classmethod
    def another_class_method(cls):
        raise NotImplementedError()

class A(Base):
    def another_instance_method(self):
        return self.an_instance_method() + 1

    @classmethod
    def another_class_method(cls):
        return cls.a_class_method() + 1

class B(Base):
    def another_instance_method(self):
        return self.an_instance_method() + 2

    @classmethod
    def another_class_method(cls):
        return cls.a_class_method() + 2

我目前的 Scala 解决方案如下:

trait Base {
  def an_instance_method(): Int = 0
  def another_instance_method(): Int
}

trait BaseCompanion {
  def a_class_method(): Int = 1
  def another_class_method(): Int
}

class A extends Base {
  override def another_instance_method(): Int = an_instance_method() + 1
}
object A extends BaseCompanion {
  override def another_class_method(): Int = a_class_method() + 1
}

class B extends Base {
  override def another_instance_method(): Int = an_instance_method() + 2
}
object B extends BaseCompanion {
  override def another_class_method(): Int = a_class_method() + 2
}

有没有更好的办法?

【问题讨论】:

  • 您认为您提出的方法有什么问题?
  • 这似乎有点多余,所以我想知道是否还有其他做法,或者是否至少有一些常见的命名约定,因为我不喜欢用“Companion”来命名相应的“companion trait” " 后缀。

标签: scala inheritance companion-object


【解决方案1】:

例如在 Shapeless 中你可以找到特征

  • ProductTypeClassProductTypeClassCompanion

  • LabelledProductTypeClassLabelledProductTypeClassCompanion

https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/typeclass.scala

所以我想命名和组织层次结构是可以的,尽管您没有提供如何使用类 A 和对象 A、类 B 和对象 B 之间的连接的详细信息。现在它们似乎是独立的,所以对象 A 现在不能必然是类 A 的伴随对象,只是一些对象 A1。

实际上我不认为这是多余的,因为这两个层次结构是两个不同的层次结构。类 A 和它的伴生对象 A 完全不同,在继承和类型上没有联系,唯一具体的是它们可以看到彼此的成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多