generics - Abstracting Common Behavior with Traits in Scala -
i have trait following:
trait mytrait[t] { def dosomething(elems: seq[t]) }
i have factory create instances of implementations of trait:
object mytrait { def apply(): mytrait = { new stringtrait() } }
now concrete implementation looks this:
class stringtrait extends mytrait[string] { def dosomething(elems: seq[string]) = { // generic logic here // specific logic here (this code bit depends on type of implementation) // generic logic here } }
how make stringtrait such pass in specific behavior , having generic logic defined in abstract class? 1 way pass in behavior thunk, wold mean have modify dosomething(...) method take additional parameter prefer avoid.
you have few options, sake of illustration i'll assume type specific behaviour seq[t] => t (i.e. take sequence of t , produce t result):
inheritance based:
trait mytrait[t] { def dotypespecificstuff(a: seq[t]): t def dosomething(elems: seq[t]): t = { // generic code stuff val t: t = dotypespecificstuff(elems) // more generic code t } } class stringtrait extends mytrait[string] { def dotypespecificstuff(elems: seq[string]) = { elems.reduceoption(_ + _).getorelse("") } } def client(thing: mytrait[string], elems: seq[string]) { thing.dosomething(elems) }
type class:
trait mytypeclass[t] { def dotypespecificstuff(a: seq[t]): t } object stringtypeclass { implicit val instance: stringtypeclass = new stringtypeclass() } class stringtypeclass extends mytypeclass[string] { def dotypespecificstuff(elems: seq[string]): string = { elems.reduceoption(_ + _).getorelse("") } } object typeclassdependentbehaviour { def dosomething[t](elems: seq[t])(implicit tp: mytypeclass[t]): t ={ //some code val stuff: t = tp.dotypespecificstuff(elems) //more generic code stuff } } def client(elems: seq[string]) { typeclassdependentbehaviour.dosomething(elems) }
Comments
Post a Comment