加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:如何引用超类中扩展类的类型?

发布时间:2020-12-16 09:06:43 所属栏目:安全 来源:网络整理
导读:有没有办法在Parent中定义类型T,这样T将始终成为扩展类的实际类型(在本例中为Child)? 在Parent中,我想强制/声明T始终是扩展类型,就像我在每个实际扩展类中写入类型T =“type_of_the_extending_class”而没有实际写下Child1中的行类型T = Child1等. 所以Chil
有没有办法在Parent中定义类型T,这样T将始终成为扩展类的实际类型(在本例中为Child)?

在Parent中,我想强制/声明T始终是扩展类型,就像我在每个实际扩展类中写入类型T =“type_of_the_extending_class”而没有实际写下Child1中的行类型T = Child1等.

所以Child1的方法只接受Child1对象作为参数,Child2的方法只接受Child2对象.有没有更简单的方法来强制执行此操作?有没有办法在每个ChildX类中都没有写入类型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")
}

解决方法

这个问题的标准解决方案是 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-bounded多态性的抱怨 – 例如Kris Nuttycombe说它是“tricky to get right and causes typing clutter in the codebase”,而且我个人发现在Scala写了几年之后我越来越少地使用它了.但是,当您的程序体系结构导致您需要这种继承时,它正是该工作的正确工具.

this.type(在评论中提到)的问题在于它不允许你完成大部分你想要做的事情 – 它太具体了:

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的唯一参数就是它自己.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读