I read an interesting article on <Type Classes> , ...
# getting-started
a
I read an interesting article on Type Classes , was nodding most of the way through, and this got me excited “*Type classes offer a solution by allowing us to define a set of behaviors (like validation rules) that can be applied to various types without altering them.* Now I would like to “add behavior” so that each subclass of a domain-layer sealed interface below can have a “saver” associated with it that knows how to load / save (Aaa, Bbb, Ccc) to datastore:
Copy code
sealed interface Thing {
  value class Aaa:Thing
  value class Bbb:Thing
  value class Ccc:Thing
}
This sealed hierarchy in the domain should not have serialization logic polluting it (to / from android preference datastore). If I created a Type Class
PrefSaver
like
Copy code
interface PrefSaver<T> {
    fun T.save(prefs)
    fun load(prefs):T
}
And then do something like
Copy code
value AaaSaver = object:PrefSaver<Aaa> {
  ....
}
How can I associate the subclass with the actual saver? In the article I see things like
Copy code
with (AaaSaver) {
    do something
}
But I can’t figure out how , if you only know the base class
Thing
, to associate the Type Class Instance for it:
Copy code
fun process(thing:Thing) {
    val saverForThing = ???
    with (saverForThing) { ... }
}
All I could think of was pattern matching using
when
, but the article seems to imply this could be eliminated. I was trying to move away from
Copy code
when (thing) {
  is Aaa -> save(aaa)
  is Bbb -> save(bbb)
  is Ccc -> save(ccc)
}
c
It's not possible at the moment, type-classes don't actually exist in Kotlin. The easiest solution;
Copy code
val Thing.saver get() = object : PrefSaver<Thing> {
    // …
}
this way you can:
Copy code
fun process(thing: Thing) {
    with (thing.saver) { ... }
}
👍 1
w
Okay, I really like this topic, so I'm digging in to your query :). First of all, what Ivan means with "we don't have type classes" is only that we don't "magically introduce" them. You can still get the structural advantages of type classes, but unlike some languages, we won't automatically pick your type classes. Anyhow, even in languages that have typeclass support, you'd have to do the pattern match expression if you want a
PrefSaver<Thing>
. I don't exactly see the syntax you are hoping to achieve.
👍 1