TypeTag equality and application to KMap

19 views
Skip to first unread message

Tomas Mikula

unread,
Oct 16, 2016, 12:31:55 AM10/16/16
to scala-debate
Hi,

my first question is, is it well defined to compare TypeTags for equality?
Is it correct to assume that

    (ta: TypeTag[A]) == (tb: TypeTag[B])

if and only if

    A =:= B

?

Scaladoc for TypeTags doesn't say anything about testing TypeTags for equality.

If the above assumption is correct, it would be useful to have the following `equalTypes` method on TypeTag:

    trait TypeTag[A] {
        def equalTypes[B](that: TypeTag[B]): Option[A =:= B]
    }

so that we could go from TypeTag equality to type equality, effectively giving us runtime type equality.


One application of TypeTag equality would be a type-safe KMap implementation:

    trait KMap[K[_], V[_]] {
      def put[A](k: K[A], v: V[A]): KMap[K, V]
      def get[A](k: K[A]): Option[V[A]]
      def remove[A](k: K[A]): KMap[K, V]
    }

In general, the `get` method above is not type-safe if there is a possibility of

    (k1: K[A]) == (k2: K[B])

while A and B are different types. This would be the case for, say

    case class Key[A](value: Long)

because we have

    Key[Boolean](42) == Key[String](42)

even though Boolean =/= String.

We could make the KMap type-safe by storing a TypeTag alongside the key, and changing the API to

    trait KMap[K[_], V[_]] {
      def put[A: TypeTag](k: K[A], v: V[A]): KMap[K, V]
      def get[A: TypeTag](k: K[A]): Option[V[A]]
      def remove[A: TypeTag](k: K[A]): KMap[K, V]
    }

i.e. adding the TypeTag context bound to all methods.

Is this a reasonable thing to do?

Best,
Tomas
Reply all
Reply to author
Forward
0 new messages