Jun. 27th, 2014
scala type classes, twittered
Jun. 27th, 2014 10:07 pm- what are they?
Classes of types, not formally declared as classes, as they usually do in Java/Scala.
- why?
To provide common, context-based ad-hoc operations, not provided by the types (since we don't want to). E.g. you have a traditional Java array, and you want it to be smarter.
- where do I declare additional operations?
Declare a parameterized trait e.g.
- where do I define additional operations?
In an implicit witness object implementing the trait.
- how do I use it?
(Using pimp pattern) define an implicit function that takes an instance of
- how come the right functionality is involved?
Compiler finds the right witness object based on the parameter type. Make sure there's exactly one visible for your type.
==========
P.S. correct me if I am wrong.
Classes of types, not formally declared as classes, as they usually do in Java/Scala.
- why?
To provide common, context-based ad-hoc operations, not provided by the types (since we don't want to). E.g. you have a traditional Java array, and you want it to be smarter.
- where do I declare additional operations?
Declare a parameterized trait e.g.
NewOps[T]
that describes the type class with functionality applicable to T
.- where do I define additional operations?
In an implicit witness object implementing the trait.
- how do I use it?
(Using pimp pattern) define an implicit function that takes an instance of
T
returning an instance having additional operations. Define a witness in this function implicitly - compiler will find it. Call witness object to do the job inside this new instance.- how come the right functionality is involved?
Compiler finds the right witness object based on the parameter type. Make sure there's exactly one visible for your type.
==========
P.S. correct me if I am wrong.