Scala: How to make requirements of the type parametres of generic classes? -
i'm creating parameterized classes c[t] , want make requirements of characteristics of type t able parameter of class. simple if wanted t inherited traits or classes (as ordering). want implement functions well.
for example, i've seen many pre-defined types implement minvalue , maxvalue, type t implement these too. i've received advice define implicit function. wouldn't users obliged implement function these when implemented. implement them @ code too, seems poor quick fix.
for example, when defining heaps, allowd users construct empty heap. in these cases want inicialize value minimum value type t have. code not works.
class heap[t](val value:t,val heaps:list[heap[t]]){ def this()=this(t.minvalue,list()) } i love receive advice online scala 2.8 references.
a bunch of things, loosely related virtue of sharing few methods (though different return types). sure sounds ad-hoc polymorphism me!
roll on type class...
class hasminmax[t] { def maxvalue: t def minvalue: t } implicit object inthasminmax extends hasminmax[int] { def maxvalue = int.maxvalue def minvalue = int.minvalue } implicit object doublehasminmax extends hasminmax[double] { def maxvalue = double.maxvalue def minvalue = double.minvalue } // etc class c[t : hasminmax](param : t) { val bounds = implicitly[hasminmax[t]] // use bounds.minvalue or bounds.minvalue required } update
the [t : hasminmax] notation context bound, , syntactic sugar for:
class c[t](param : t)(implicit bounds: hasminmax[t]) { // use bounds.minvalue or bounds.minvalue required }
Comments
Post a Comment