简体   繁体   English

在返回实际类型的协变特征中“返回此”

[英]“return this” in a covariant trait that return actual type

This was probably asked before, but I have this problem: 这可能是之前提出的问题,但我有这个问题:

trait Container[+A] {
  def a: A

  def methodWithSideEffect() = {
    // perform some side effecting work
    this
  }
}

class IntContainer(val a: Int) extends Container[Int]

How do I have the methodWithSideEffect in IntContainer return an IntContainer instead of a Container[Int] ? 如何在methodWithSideEffect中使用IntContainer返回IntContainer而不是Container[Int] I would also want not to add any parameter to the Container trait, at least from the API user point of view. 我还希望不向Container特征添加任何参数,至少从API用户的角度来看。 Note that I did make a workaround with an implicit: 请注意,我确实使用隐式进行了解决方法:

implicit class MyContainer[A <: Container[_]](c: A) {
  def methodWithSideEffect(): A = {
    // perform work
    c
  }
}

However, I am quite sure there is some way to do this more elegantly. 但是,我确信有一些方法可以更优雅地完成这项工作。

You can do this with a self type: 您可以使用自我类型执行此操作:

trait Container[+A] { self =>
  def a: A

  def methodWithSideEffect(): self.type = {
    // perform some side effecting work
    this
  }
}

class IntContainer(val a: Int) extends Container[Int]

... ...

val x: IntContainer = new IntContainer(42).methodWithSideEffect()

Or simply with this.type : 或者只是使用this.type

trait Container[+A] {
  def a: A

  def methodWithSideEffect(): this.type = {
    // perform some side effecting work
    this
  }
}

class IntContainer(val a: Int) extends Container[Int]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM