【问题标题】:Scala: how to refer to the type of an extending class in a superclass?Scala:如何在超类中引用扩展类的类型?
【发布时间】:2014-02-11 19:22:38
【问题描述】:

有没有办法在 Parent 中定义一个类型 T 使得 T 总是成为扩展类的实际类型(在这种情况下是 Child)?

在Parent 中,我想强制/声明T 始终是扩展类型,就好像我会在每个实际扩展类中编写type T="type_of_the_extending_class" 而不实际写下@987654328 中的type T=Child1 行@等

所以 Child1 的方法应该只接受 Child1 对象作为参数,而 Child2 的方法应该只接受 Child2 对象。有没有更简单的方法来执行此操作?有没有在每个 ChildX 类中不写 type T=ChildX 的方法?有没有这个样板的方法?

我一直在 Scala 书籍中寻找解决方案,但没有找到。

abstract class Parent{
  type T<:Parent
  def method(t:T) 
}

class Child1 extends Parent{
  type T=Child1
  override def method(t:T)=t.child1method
  def child1method=println("child1's method")
}

class Child2 extends Parent{
  type T=Child2
  override def method(t:T)=t.child2method
  def child2method=println("child2's method")
}

【问题讨论】:

  • 你试过“this.type”吗?
  • @stefan.schwetschke 这是正确的解决方案。你应该添加它是一个答案
  • 实际上this.type 可能不是正确的解决方案——请参阅下面的答案。
  • 特拉维斯布朗是正确的。 this.type 是限制性的。同一个子类的两个实例有不同的this.type。

标签: scala types


【解决方案1】:

这个问题的标准解决方案是F-bounded polymorphism(它不是 Scala 特有的——你会发现它用在 Java 等中):

trait Parent[T <: Parent[T]] {
  def method(t: T)
}

class Child1 extends Parent[Child1] {
  def method(t: Child1) = println("child1's method")
}

class Child2 extends Parent[Child2] {
  def method(t: Child2) = println("child1's method")
}

附带说明一下,在 Scala 社区中有一些关于 F 有界多态性的抱怨——例如 Kris Nuttycombe 说它是 "tricky to get right and causes typing clutter in the codebase",我个人发现我使用它的次数较少在编写 Scala 几年后,这种情况就不那么频繁了。但是,当您的程序架构导致您需要这种继承时,它正是适合这项工作的工具。

this.type(在 cmets 中提到)的问题在于它不允许你做大部分你合理想做的事情——它太具体了:

scala> abstract class Parent {
     |   def method(t: this.type)
     | }
defined class Parent


scala> class Child1 extends Parent {
     |   def method(t: this.type) = println("child1's method")
     | }
defined class Child1

scala> val a = new Child1
a: Child1 = Child1@19517e9a

scala> val b = new Child1
b: Child1 = Child1@5737e545

scala> a.method(b)
<console>:12: error: type mismatch;
 found   : b.type (with underlying type Child1)
 required: a.type
              a.method(b)
                       ^

我们可以传递给a.method 的唯一参数是a 本身。

【讨论】:

  • 看了答案,觉得真的不错。它通过指向有见地的概念(F 有界多态性)的指针回答了我所有的子问题。然后我明白了原因:你写的,特拉维斯 :)
猜你喜欢
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2014-06-30
  • 2019-05-24
  • 2019-08-31
  • 2019-05-11
相关资源
最近更新 更多