简体   繁体   中英

Splitting a scala class while preserving thisful access

I split a large class into a class and a trait that mixes into the class. What are my options for accessing members of the class from the trait?

A simplified depiction of the task at hand:

class A extends B {
  def someA = 3
}

trait B {
  def someB = someA + 3 
}

Currently I require an object of type A as an argument in each member function of B, unlike shown above, which of course works, like so:

trait B {
  def someB(a: A) = a.someA + 3 // not found: value SomeA
}

Could be nice having something like the code above that works, or a this or self of a sort to use in the trait.

Motivation being less changes when moving methods around between the class and traits, and code looking quite the same in both locations. One way I know of is a self-type. Anything else?

One way to do it is to use self type, as you have mentioned:

class A extends B {
  def someA = 3
}

trait B {
  this: A =>
  def someB = someA + 3
}

The other is to have someA as an abstract method in B , and have A provide the concrete implementation for it:

class A extends B {
  def someA = 3
}

trait B {
  def someA: Int
  def someB = someA + 3
}

Or alternatively have this method defined higher in the subtype hierarchy, which is useful if several traits A depends on have to use someA

class A extends B {
  def someA = 3
}

trait B extends C {
  def someB = someA + 3
}

trait C {
  def someA: Int
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM