In Haskell you can construct parametrized types as in the following example:
data Tree a = Leaf | Node a (Tree a) (Tree a)
..and afterwards make them an instance of a typeclass if the type parameter is also an instance of the very same typeclass (Eq is used as an example here, it could be anything):
instance (Eq m) => Eq (Tree m) where
Leaf == Leaf = True
Node a b c == Node x y z = (a == x) && (b == y) && (c == z)
_ == _ = False
I am wondering how a similar thing would be possible in Scala. To start let's create the parametrized type:
abstract class Tree[T]
case class Leaf[T]() extends Tree [T]
case class Node[T](value: T, left: Tree[T], right: Tree[T]) extends Tree [T]
..and pick an even simpler trait as the typeclass being implemented:
trait Serializable {
def toDifferentString(): String
}
Now what I'd like be able to do is provide an implementation of the Serializable
trait for Tree
, if The T
type is Serializable
.
I can see a couple of ways of how to do it partially, but none that would get me the Haskell-like result:
- add a type constraint
:<
in theTree
abstract class, but then it's getting less generic and I'm assuming I can modify theTree
class - create an implicit conversion from
Tree[Serializable]
toSerializable
, but I'm not even sure it would work and how robust it would be.
What is a good way of approaching the issue?