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 =>
thisis not a field.You can't assign or re-assign its value but with
this: T => ...orany_name: T => ...you can specify that all implementations must be subtypes ofT(withany_name =>you just introduce an alias forthis).If you want to specify that all implementations of
DepositAccountmust be subtypes both ofAccountandProfileyou can use intersection types (within Scala 2,&in Scala 3)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