如何使用Scala的this类型、抽象类型等来实现Self类型?

发布于 2024-10-05 07:50:31 字数 735 浏览 3 评论 0原文

我在其他问题中找不到这个问题的答案。假设我有一个抽象超类 Abstract0,它有两个子类:Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类似

def setOption(...): Self = {...}

Self 是具体子类型的内容。这将允许像这样链接调用 setOption:

val obj = new Concrete1.setOption(...).setOption(...)

并且仍然将 Concrete1 作为 obj 的推断类型。

我不想定义这个:

abstract class Abstract0[T <: Abstract0[T]]

因为它使客户端更难处理这种类型。我尝试了各种可能性,包括抽象类型:

abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}

但是不可能实现 setOption,因为 Abstract0 中的 this 没有 Self 类型。并且使用 this: Self => 在 Abstract0 中也不起作用。

对于这个问题有哪些解决方案呢?

I couldn't find the answer to this in any other question. Suppose that I have an abstract superclass Abstract0 with two subclasses, Concrete1 and Concrete1. I want to be able to define in Abstract0 something like

def setOption(...): Self = {...}

where Self would be the concrete subtype. This would allow chaining calls to setOption like this:

val obj = new Concrete1.setOption(...).setOption(...)

and still get Concrete1 as the inferred type of obj.

What I don't want is to define this:

abstract class Abstract0[T <: Abstract0[T]]

because it makes it harder for clients to handle this type. I tried various possibilities including an abstract type:

abstract class Abstract0 {
  type Self <: Abstract0
}

class Concrete1 extends Abstract0 {
  type Self = Concrete1
}

but then it is impossible to implement setOption, because this in Abstract0 does not have type Self. And using this: Self => also doesn't work in Abstract0.

What solutions are there to this issue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

活雷疯 2024-10-12 07:50:31

这就是 this.type 的用途:

scala> abstract class Abstract0 {
     |   def setOption(j: Int): this.type
     | }
defined class Abstract0

scala> class Concrete0 extends Abstract0 {
     |   var i: Int = 0
     |   def setOption(j: Int) = {i = j; this}
     | }
defined class Concrete0

scala> (new Concrete0).setOption(1).setOption(1)
res72: Concrete0 = Concrete0@a50ea1

如您所见,setOption 返回实际使用的类型,而不是 Abstract0。如果 Concrete0 有 setOtherOption 那么 (new Concrete0).setOption(1).setOtherOption(...) 就可以了

更新:回答 JPP 在评论中的后续问题(如何返回新实例:
问题中描述的一般方法是正确的(使用抽象类型)。然而,对于每个子类来说,新实例的创建需要是明确的。

一种方法是:

abstract class Abstract0 {
  type Self <: Abstract0

  var i = 0

  def copy(i: Int) : Self

  def setOption(j: Int): Self = copy(j)
}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
  def copy(i: Int) = new Concrete0(i)
}

另一种方法是遵循 Scala 集合库中使用的构建器模式。也就是说,setOption 接收隐式构建器参数。这样做的优点是可以使用更多方法来构建新实例,而不仅仅是“复制”,并且可以完成复杂的构建。例如,setSpecialOption 可以指定返回实例必须是 SpecialConcrete。

这是解决方案的说明:

trait Abstract0Builder[To] {
    def setOption(j: Int)
    def result: To
}

trait CanBuildAbstract0[From, To] {
  def apply(from: From): Abstract0Builder[To]
}


abstract class Abstract0 {
  type Self <: Abstract0

  def self = this.asInstanceOf[Self]

  def setOption[To <: Abstract0](j: Int)(implicit cbf: CanBuildAbstract0[Self, To]): To = {
    val builder = cbf(self)
    builder.setOption(j)
    builder.result
  }

}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
}

object Concrete0 {
    implicit def cbf = new CanBuildAbstract0[Concrete0, Concrete0] {
        def apply(from: Concrete0) = new Abstract0Builder[Concrete0] {
           var i = 0
           def setOption(j: Int) = i = j
           def result = new Concrete0(i)
        }
    }
}

object Main {
    def main(args: Array[String]) {
    val c = new Concrete0(0).setOption(1)
    println("c is " + c.getClass)
    }
}

更新 2:
回复 JPP 的第二条评论。如果有多层嵌套,请使用类型参数而不是类型成员,并将 Abstract0 设为特征:

trait Abstract0[+Self <: Abstract0[_]] {
  // ...
}

class Concrete0 extends Abstract0[Concrete0] {
  // ....
}

class RefinedConcrete0 extends Concrete0 with Abstract0[RefinedConcrete0] {
 // ....
}

This is what this.type is for:

scala> abstract class Abstract0 {
     |   def setOption(j: Int): this.type
     | }
defined class Abstract0

scala> class Concrete0 extends Abstract0 {
     |   var i: Int = 0
     |   def setOption(j: Int) = {i = j; this}
     | }
defined class Concrete0

scala> (new Concrete0).setOption(1).setOption(1)
res72: Concrete0 = Concrete0@a50ea1

As you can see setOption returns the actual type used, not Abstract0. If Concrete0 had setOtherOption then (new Concrete0).setOption(1).setOtherOption(...) would work

UPDATE: To answer JPP's followup question in the comment (how to return new instances:
The general approach described in the question is the right one (using abstract types). However, the creation of the new instances needs to be explicit for each subclass.

One approach is:

abstract class Abstract0 {
  type Self <: Abstract0

  var i = 0

  def copy(i: Int) : Self

  def setOption(j: Int): Self = copy(j)
}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
  def copy(i: Int) = new Concrete0(i)
}

Another one is to follow the builder pattern used in Scala's collection library. That is, setOption receives an implicit builder parameter. This has the advantages that building the new instance can be done with more methods than just 'copy' and that complex builds can be done. E.g. a setSpecialOption can specify that the return instance must be SpecialConcrete.

Here's an illustration of the solution:

trait Abstract0Builder[To] {
    def setOption(j: Int)
    def result: To
}

trait CanBuildAbstract0[From, To] {
  def apply(from: From): Abstract0Builder[To]
}


abstract class Abstract0 {
  type Self <: Abstract0

  def self = this.asInstanceOf[Self]

  def setOption[To <: Abstract0](j: Int)(implicit cbf: CanBuildAbstract0[Self, To]): To = {
    val builder = cbf(self)
    builder.setOption(j)
    builder.result
  }

}

class Concrete0(i: Int) extends Abstract0 {
  type Self = Concrete0
}

object Concrete0 {
    implicit def cbf = new CanBuildAbstract0[Concrete0, Concrete0] {
        def apply(from: Concrete0) = new Abstract0Builder[Concrete0] {
           var i = 0
           def setOption(j: Int) = i = j
           def result = new Concrete0(i)
        }
    }
}

object Main {
    def main(args: Array[String]) {
    val c = new Concrete0(0).setOption(1)
    println("c is " + c.getClass)
    }
}

UPDATE 2:
Replying to JPP's second comment. In case of several levels of nesting, use a type parameter instead of type member and make Abstract0 into a trait:

trait Abstract0[+Self <: Abstract0[_]] {
  // ...
}

class Concrete0 extends Abstract0[Concrete0] {
  // ....
}

class RefinedConcrete0 extends Concrete0 with Abstract0[RefinedConcrete0] {
 // ....
}
风追烟花雨 2024-10-12 07:50:31

这是 this.type 的确切用例。它会像:

def setOption(...): this.type = { 
  // Do stuff ...
  this
}

This is the exact use case of this.type. It would be like:

def setOption(...): this.type = { 
  // Do stuff ...
  this
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文