scala - 具有另一个类的 self 类型的类是否有意义?

标签 scala self-type

scala> class A
defined class A

scala> class B {this: A => }
defined class B

scala> new B
<console>:10: error: class B cannot be instantiated because it does not conform
to its self-type B with A
             new B
             ^

类(class)B将 self 类型设置为 class A ,因此类 B (或其子类)必须扩展类 A创建 B 的实例.但这是否可能,因为 B 的子类只能扩展一个类(这是类 B )?

所以这让我想到了一个问题,在任何情况下将一个类的 self 类型声明为另一个类是否有意义?

最佳答案

您的观察是正确的,该定义不能导致具体的实现,因为您不能混合两个类,只能混合特征。所以简短的回答是“不”,两者都应该是一个特征。

Stackoverflow 上有几个关于 self-types 的问题。两个有用的是这些:

  • What is more Scala idiomatic: trait TraitA extends TraitB or trait TraitA { self: TraitB => }
  • Difference between trait inheritance and self type annotation

  • 在第二个问题中,Ben Lings 给出了一个很好的答案,他引用了 Spiros Tzavellas 博客中的以下段落。 :

    In conclusion, if we want to move method implementations inside traits then we risk polluting the interface of those traits with abstract methods that support the implementation of the concrete methods and are unrelated with the main responsibility of the trait. A solution to this problem is to move those abstract methods in other traits and compose the traits together using self type annotations and multiple inheritance.



    例如,如果 A (假设它现在是一个特征而不是一个类!)是一个记录器。您不想为 B 公开公开混入的日志 API A .因此,您将使用 self-type 而不是 mixin。内执行B您可以调用日志记录 API,但从外部看它是不可见的。

    另一方面,您可以使用以下形式的组合:
    trait B {
        protected def logger: A
    }
    

    现在的区别在于
  • B必须引用logger想要使用其功能时
  • B 的亚型有权访问 logger
  • BA不要在命名空间中竞争(例如可以有相同名称的方法而不会发生冲突)

  • 我会说自类型是 Scala 的一个相当外围的特性,在很多情况下你不需要它们,并且你有这样的选择来实现几乎相同的无自类型。

    关于scala - 具有另一个类的 self 类型的类是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11274106/

    相关文章:

    scala - Json Coast to Coast Play框架: Serializing Joda DateTime

    java - 为什么我们需要在 Scala 中为 Double 传递指数形式的数字?

    scala - 将数字相加

    scala - 在 Scala 的父特性中声明子特性的 self 类型

    scala - Scala self 类型可以强制执行案例类类型吗

    scala - 在 Scala 中使用 self 类型时如何保持单一责任?

    scala - Scala 中涉及函数依赖的泛型编程和烂香蕉

    scala - 如何检测 Scala 中的无穷大值?

    Scala:父类是否可以访问仅由子级定义的方法?

    scala - 具有更高种类类型的类的自类型注释