Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

But both Java and Kotlin interfaces can provide default implementations. So when I say "make a class implement an interface even if it doesn't declare it as so", that included interface default methods coming along for the ride.

The best explanation of Scala type classes IMO is here:

  http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html
But as you say, what Scala calls type classes are more of a pattern with some language support - you just define what is essentially an adapter, but one which is constructed/used implicitly.

Being able to write:

  interface Foo {
      val prop: String
      fun someMethod() = "we are set to $prop"
  }
and then being able to treat any Bar as Foo as long as it has some property "prop" but without regard for whether it has someMethod, sounds pretty much the same thing as Haskell/Scala's idea of type classes to me.


It's not just a default, you can provide an adapter specific to the type:

    implicit object IntMonoid extends Monoid[Int] {
      def zero = 0
      def plus(a: Int, b: Int) = a + b
    }
    implicit def endoMonoid[A] = new Monoid[A => A] {
      def zero = identity
      def plus(a: A => A, b: A => A) = a andThen b
    }
You can't do that with a default method.


While it's an excellent example, I wonder if people don't see "endoMonoid" and run away screaming.

I really wonder if people would have different reactions if this was presented as "Addable" instead.


Yeah, I wonder about calling it "addable" or "mergeable". But neither of those really captures the full generality of it - would you expect composing functions to count as "adding" or "merging"?


"Combinable"?

Integers can also be combined with other operations, like multiplication, min or max. None of those sound like "adding" or "merging" them to me.


Good point. Though a good side effect is that when you see it used that way you "a-ha!", or you figure it yourself you feel smart. Something like "endoMonoid" doesn't immediately suggest these use cases either (unless you're a math buff) but if you get to the explanation you're just left with the feeling that this is what was intended all along, not a neat breakthrough.

That's reverse API psychology for you :D




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: