8 ms·
By typeclasses, do you mean structural typing a.k.a. duck typing a.k.a. Go-style interfaces? I don't personally understand why people care about that: a simple
by mike_hearn 11y ago
By typeclasses, do you mean structural typing a.k.a. duck typing a.k.a. Go-style interfaces?
I don't personally understand why people care about that: a simple structural match on names/parameter types doesn't seem like a strong enough signal that someone actually intended to implement such an interface.
But ... type classes can be implemented on the JVM relatively efficiently these days. I threw together a simple Kotlin version a few weeks ago that let you write something like:
val foo = Foo()
val bar = foo.dynamicCast<Bar>()
where Bar was an interface that Foo could have implemented but didn't. It worked, but I didn't see any value in it for myself, and it didn't use the latest JVM reflection APIs so it was slower than a normal interface call.
If there's some big population of people who really want this in Kotlin and would be much happier if they had it, then I might sit down and reimplement it on top of Remi Forax's proxy2 framework, which should give 1:1 native performance.
- lmm 11y agoNo. Structural types are called structural types. The best known typeclass implementation is that of Haskell where they're built into the language, but Scala has them as a pattern implemented with implicits; I can try to explain the concept here if you like but honestly there are probably better explanations out there. Typeclasses are more powerful than structural types in that the implementation doesn't have to be there already (i.e. you can have an automatically resolved adapter). You might be able to hack an implementation by combining extension methods with structural types (though given the internals of how extension methods are usually implemented on the JVM I doubt it). They also allow a way to do "static virtual methods" i.e. polymorphic methods that you don't need an instance to invoke, which are used for things like Monoid#zero. Finally they provide a nicer way to express F-bounded polymorphism (i.e. the constraint on Enum or Comparable that we try to express in Java as Enum<E extends Enum<E>> or Comparable<T extends Comparable<T>>, which is clunky and doesn't actually fully constrain implementations the way it's intended to).
- mike_hearn 11y agoBut 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.
- lmm 11y agoIt'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.
- norswap 11y agoWhile 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.
- bad_user 11y ago> The best known typeclass implementation is that of Haskell Oh, I don't know about that one. In Scala type-classes are interfaces and you can put that OOP to good use. For example in the Cats library, you get an Applicative type-class inheriting from Apply, a FlatMap inheriting from Apply and a Monad inheriting from FlatMap and Applicative. By comparison in Haskell a Monad is not automatically an Applicative and you get duplicate functions with different names, duplicate code, duplicate tests, etc. Another advantage is that in Scala type-class instances are actual values that you can pass around. And because type-class instances are actual values, along with implicits which are lexically scoped, you can always provide another instance of a type-class, depending on context. You do not have the modularity problems arising from usage of type-classes in Haskell. "The best implementation" is entirely subjective IMHO. EDIT: got down-votes, not complaining, but I'd like to know where I'm mistaken. Thanks.
- koloron 11y agoDidn't downvote, just FYI: Haskell's Applicative is a superclass of Monad now.
- Chattered 11y agoWhich means you are now forced to write the boilerplate pure = return (<*>) = liftM2 ($) In Scala, you get it for free for any monad.
- koloron 11y agoSince GHC-7.10, the minimal complete definition for a Monad instance has been (>>=) (bind) only. So you can simply move the old definition for "return" into the Applicative instance as "pure" and you're good.
- extempore 11y agoHe means best-known, not best known. It's a statement about which is better known, not which is better.
- pdpi 11y agoIt's nothing like duck typing -- type classes are a major thing in Haskell, which should tell you how far from duck typing it is ;) They're also present in Scala (as the OP mentioned), in Rust as Traits, and C++11 had a proposal for Concepts, which are quite similar as well. The short but slightly inaccurate description is that type classes are a way to allow interfaces to be implemented separately from the way you define types.
- norswap 11y agoNo, not that. I agree with you on structural typing. What I mean is what the Scala doc calls "context bounds": http://docs.scala-lang.org/tutorials/FAQ/context-and-view-bounds.html http://docs.scala-lang.org/tutorials/FAQ/context-and-view-bo... (bit outdated: view bounds are deprecated) You could think of it as "abstracting over the adapter pattern", i.e. being able to write methods that take as parameter things that can be adapted to an interface. (And of course the main point of the Adapter pattern is retroactive implementation of interfaces.) But, and this is important, you get to pass the actual object instead of the adapter. This matters when you need to required multiple adapters, or when you work with object equality. The object type can also flow through the type parameters (although that's sort of doable with adapters only). Finally, because a typeclass instance is actually a single object per type satisfying an interface, you can use it for things like factory methods (what they call constructor classes in Haskell). It's close to what I propose here: https://discuss.kotlinlang.org/t/kotlin-and-the-expression-problem/1416 https://discuss.kotlinlang.org/t/kotlin-and-the-expression-p... but there are differences. Scala typeclasses are based on implicits, this gives you more control to select the adapter you want depending on where the code runs. But, unlike what I propose, it's dependent on static typing, so it's not possible to select the adapter depending on the run-time type.
- mike_hearn 11y agoRight, I remember your thread, which is I guess why I'm a bit confused, as you said what you really wanted to do is make a type implement a new interface. I do understand Haskell type classes but in a language like that, they're almost obligatory as it's not an OO language at all. But in something like Kotlin, you should need it far more rarely, so the automatic/implicit "conversion" (I realise it's not quite "conversion" in Haskell) is less vital. So some convenience for creation of adapters would seem to get you the same practical benefits in much the same way. With respect to the difference between using a singleton vs a freshly allocated wrapper - is it really worth complicating the Java interop for what seems like an optimisation? Code that works with object identity is rare in all the code I've written and can't even be done at all in a pure functional language. And requiring multiple 'adapters', you mean interfaces I think (?) can be done already by imposing multiple generic type constraints (the where clause). The VM should be able to optimise out the overhead of the wrapper class in many cases. That leaves implicit conversion. But Kotlin doesn't even auto-convert Int to Long. I doubt that implicit conversion will ever be a part of the language outside of a few special cases like toString(). I guess for my use cases, a wrapper class + an extension method on the existing type that adds a toFoo() is sufficient.
- bad_user 11y agoGo's interfaces are not type-classes and type-classes aren't about structural typing.