Implicit conversion vs. type class

后端 未结 3 566
广开言路
广开言路 2020-12-04 05:59

In Scala, we can use at least two methods to retrofit existing or new types. Suppose we want to express that something can be quantified using an Int. We can de

3条回答
  •  醉酒成梦
    2020-12-04 06:39

    You can think of the difference between the two techniques by analogy to function application, just with a named wrapper. For example:

    trait Foo1[A] { def foo(a: A): Int }  // analogous to A => Int
    trait Foo0    { def foo: Int }        // analogous to Int
    

    An instance of the former encapsulates a function of type A => Int, whereas an instance of the latter has already been applied to an A. You could continue the pattern...

    trait Foo2[A, B] { def foo(a: A, b: B): Int } // sort of like A => B => Int
    

    thus you could think of Foo1[B] sort of like the partial application of Foo2[A, B] to some A instance. A great example of this was written up by Miles Sabin as "Functional Dependencies in Scala".

    So really my point is that, in principle:

    • "pimping" a class (through implicit conversion) is the "zero'th order" case...
    • declaring a typeclass is the "first order" case...
    • multi-parameter typeclasses with fundeps (or something like fundeps) is the general case.

提交回复
热议问题