Scala:在父方法中维护子类? [英] Scala: Maintain child class in parent methods?

查看:107
本文介绍了Scala:在父方法中维护子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您有父母时:

abstract class Parent {
   def something(arg: ???): Parent = ???
}

class Child extends Parent {}

我想要

val updatedChild = new Child().something(...)

updatedChild属于类型Child而不是类型Parent,这可能吗?

解决方案

一种方法是参数化父对象:

 abstract class Parent[T <: Parent[T]] {
    def something(arg: Foo): T
 }

 class Child(val foo: String) extends Parent[Child] {
    def something(arg: String) = return new Child(arg)
 }

有时候,您也可以使用this.type:

class Parent {
  def something(arg: Foo): this.type = this
}
class Child {
   override def something(arg: Foo) = this
}

但是后一种方法仅在您要返回的全部是this时才有效(this.type不是ParentChild,而是仅具有一个实例的特定类型-this)./p>

When you have a parent:

abstract class Parent {
   def something(arg: ???): Parent = ???
}

and

class Child extends Parent {}

I would like

val updatedChild = new Child().something(...)

updatedChild to be of type Child and not of type Parent, is it possible ?

解决方案

One way to do it, is to parametrize the parent:

 abstract class Parent[T <: Parent[T]] {
    def something(arg: Foo): T
 }

 class Child(val foo: String) extends Parent[Child] {
    def something(arg: String) = return new Child(arg)
 }

Sometimes, you can also get away with using this.type:

class Parent {
  def something(arg: Foo): this.type = this
}
class Child {
   override def something(arg: Foo) = this
}

But the latter method only works if all you ever want to return is this (this.type is not Parent or Child, but a specific type that only has one instance - this).

这篇关于Scala:在父方法中维护子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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