Why cannot this.type be used for new instances

前端 未结 2 1249
灰色年华
灰色年华 2021-01-04 03:40

I\'d like to be able to use this.type to define a method that makes new instances of an immutable case class. Something like this:

trait Expression
{
  def          


        
2条回答
  •  时光取名叫无心
    2021-01-04 04:25

    this.type is the unique type of this particular instance. It's a singleton type - a distinct type from any other instance of the same class. This works

    class Foo { def f : this.type = this}
    

    But this does not

    class Foo { def f : this.type = new Foo}
    

    this.type isn't needed that often, but it can be used to express some constraints that can't be expressed otherwise

    For instance, here the Inner class says each instance's outer method will return the specific Outer instance from which it came.

    scala> class Outer{ class Inner { def outer : Outer.this.type = Outer.this}; def f(x : Inner) = println("ok")}
    defined class Outer
    
    scala> val o1 = new Outer
    o1: Outer = Outer@13c1b69
    
    scala> val o2 = new Outer
    o2: Outer = Outer@1a3f178
    
    
    scala> val in1 = new o1.Inner
    in1: o1.Inner = Outer$Inner@627b5c
    
    scala> val in2 = new o2.Inner
    in2: o2.Inner = Outer$Inner@158c3b7
    
    scala> val o3 = in1.outer
    o3: o1.type = Outer@13c1b69
    
    scala> o1.f(new o3.Inner)  
    ok
    
    scala> o1.f(new o2.Inner)
    :8: error: type mismatch;
     found   : o2.Inner
     required: o1.Inner
           o1.f(new o2.Inner)
    

    This article has another nice example of using this.type to enable method chaining across subclass boundaries: http://scalada.blogspot.com/2008/02/thistype-for-chaining-method-calls.html

    scala>   class A { def method1: this.type = this }
    defined class A
    
    scala>   class B extends A { def method2: this.type = this }
    defined class B
    
    scala> val b = new B
    b: B = B@15cb235
    
    scala> b.method1.method2
    res3: b.type = B@15cb235
    

提交回复
热议问题