How to use Scala's this typing, abstract types, etc. to implement a Self type?
Solution 1:
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] {
// ....
}
Solution 2:
This is the exact use case of this.type
. It would be like:
def setOption(...): this.type = {
// Do stuff ...
this
}