Scala:如何编写返回类型为接收器实现类型的对象的方法 [英] Scala: how to write method that returns object typed to implementation type of receiver

查看:41
本文介绍了Scala:如何编写返回类型为接收器实现类型的对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在 Scala 中不推荐使用 case 类继承,但为了简单起见,我在以下示例中使用了它:

I'm aware that case class inheritance is deprecated in Scala, but for the sake of simplicity, I've used it in the following example:

scala> case class Foo(val f: String) { def foo(g: String): Foo = { this.copy(f=g) }}
defined class Foo

scala> case class Bar(override val f: String) extends Foo(f)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
defined class Bar

scala> Bar("F")
res0: Bar = Foo(F)

scala> res0.foo("G")
res1: Foo = Foo(G)

到目前为止,一切都很好.不过,我真正想要的是能够在 Foo 中编写一个方法 foo() ,该方法在调用 Bar 类型的对象时返回一个 Bar 类型的对象,而无需在班级酒吧.有没有办法在 Scala 中做到这一点?

So far, so good. What I really want, though, is to be able to write a method foo() in Foo that returns an object of type Bar when called on an object of type Bar, without having to reimplement the method in class Bar. Is there a way to do this in Scala?

推荐答案

注意:这不会创建新对象,而是重新使用 this 对象.对于一般用途,请参阅 范式的答案.

Note: This does not create a new object but re-uses the this object. For general use, see paradigmatic’s answer.

由于某种原因,它不能与 case classcopy 方法一起使用.(但不可否认,既然case class 继承无论如何都不应该进行,所以问题不会发生.).但是对于任何其他方法,您可以使用 this.type.

For some reason, it does not work together with the case class’s copy method. (But admittedly, since case class inheritance should not be done anyway, the problem does not occur.). But for any other method, you do it with this.type.

case class Foo(val f: String) { def foo(g: String): this.type = { this }}

case class Bar(override val f: String) extends Foo(f)

Bar("F").foo("G")
res: Bar = Foo(F)

<小时>

如果您需要方法参数和方法主体中的自类型变化(与仅返回类型的变化相反),您将需要更进一步并定义


If you need the self-type variance in method arguments and method bodys (as opposed to return-type-only variance), you will need to go one step further and define

trait HasFoo[T <: HasFoo[T]] { this: T =>
  def foo(g:String): T
  def bar(g: T): T // here may follow an implementation
}

这将允许您向 trait 添加适当的方法主体.(请参阅:2D 和 3D 向量的正确类层次结构)

This will allow you to add proper method bodies to the trait. (See: proper class hierarchy for 2D and 3D vectors)

这篇关于Scala:如何编写返回类型为接收器实现类型的对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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