Scala reduce duplicate code from inheritance -


class characterfilter extends filter[character] {     def _name(n: string) = { data = data.filter(c => c.name == n) } } class npcfilter extends characterfilter {     def name(n: string) = { _name(n); } } class playerfilter extends characterfilter {     def name(n: string) = { _name(n); } } 

i'm building classes filter through data. npcfilter , playerfilter should share methods characterfilter. however, want each filter return @ end can chain functions this: .name("john").age(18).race(white)

at first tried this, doesn't give result want, because left characterfilter after calling name instead of npcfilter or playerfilter desired.

class characterfilter extends filter[character] {     def name(n: string) = { data = data.filter(c => c.name == n); } } class npcfilter extends characterfilter { } class playerfilter extends characterfilter { } 

so first example works how want to, feels repetitive (especially once add more functions). there way make more concise?

for particular case return this, there direct support :

def f(....) : this.type =  .... 

writing that, this valid return value, , compiler type typed target of call f.

short of particular case, if return type tied type of target, not this, need type member, or generic, such

abstract class a[t <: a[t]] {self: t =>    def f(....): t }  class b extends a[b] { ... } 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -