scalatypesself-type

Can we reassign 'this' multiple times in a trait


I am learning Scala and I was trying to figure out how 'self type' works for trait.
Especially trying out to reassign the 'this' field.
I was able to reassign 'this' once but I didn't understand how it works behind the scene. I tried to see if we can reassign this twice but it failed with a weird error.

trait DepositAccount {
    this : Account =>
    def print(): Unit = {
        println(s"Balance: $getBalance")
    }

    this: Profile =>
    def printName(): Unit = {
        println(s"Name: $getName")
    }
}

Following is the error.

';' expected but '=>' found.
this: Profile =>

Solution

  • this is not a field.

    You can't assign or re-assign its value but with this: T => ... or any_name: T => ... you can specify that all implementations must be subtypes of T (with any_name => you just introduce an alias for this).

    If you want to specify that all implementations of DepositAccount must be subtypes both of Account and Profile you can use intersection types (with in Scala 2, & in Scala 3)

    trait DepositAccount {
      this: Account with Profile =>
    
      // ...
    }
    

    https://docs.scala-lang.org/tour/self-types.html

    What is the difference between self-types and trait subclasses?

    Difference between trait inheritance and self type annotation

    Why scala self type is not a subtype of its requirement

    Explicit self-references with no type / difference with ''this''

    What is more Scala idiomatic: trait TraitA extends TraitB or trait TraitA { self: TraitB => }

    https://stackoverflow.com/questions/tagged/self-type%2bscala?tab=Votes