如何使用 Scala 的 this 类型、抽象类型等来实现 Self 类型? [英] How to use Scala's this typing, abstract types, etc. to implement a Self type?

查看:20
本文介绍了如何使用 Scala 的 this 类型、抽象类型等来实现 Self 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何其他问题中都找不到答案.假设我有一个抽象超类 Abstract0,它有两个子类 Concrete1 和 Concrete1.我希望能够在 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 = {...}

其中 Self 将是具体的子类型.这将允许像这样对 setOption 进行链接调用:

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

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

仍然得到 Concrete1 作为 obj 的推断类型.

and still get Concrete1 as the inferred type of obj.

我不想定义这个:

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
}

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

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?

推荐答案

这就是 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(...) 会起作用

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

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

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.

一种方法是:

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.

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)
    }
}

更新2:回复 JPP 的第二条评论.在多层嵌套的情况下,使用类型参数而不是类型成员并将 Abstract0 变成一个特征:

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] {
 // ....
}

这篇关于如何使用 Scala 的 this 类型、抽象类型等来实现 Self 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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