Universal Converters

I find the following snippet of code (not actual production code but similar) very useful:

implicit class AnyExtensions[A](val x: A) extends AnyVal {
  def to[B](implicit f: B => A): B = f(x)

In my personal code, this is the only way I allow an implicit def to implicitly convert a type A to type B i.e. by explicitly calling foo.to[Bar] (implicit classes are allowed for extensions/typeclasses).

This comes in handy in several ways and makes the codebase consistent and pleasant to read:

  1. I have replaced all usages of .toString with .to[String] using a Show typeclass

  2. We can convert between various collections in a consistent way e.g. list.to[Vector] instead of list.toVector
    (this currently already exists in standard library via CanBuildFrom but I have extended it to support Java collections too.)

  3. Convert between the various Java date/time classes e.g. sqlDate.to[java.time.LocalDate]

  4. HKTs are supported too e.g. sequenceOfTuple2s.to[Map] instead of sequenceOfTuple2s.toMap - cleaner library since currently .toMap is defined on the collections.

  5. Various String parsing utils e.g. string.to[Int] instead of string.toInt

  6. string.to[LocalDate] instead of Localdate.parse(string) etc. using a Read typeclass.

  7. Seamless converting to/from Java e.g. scalaList.to[java.util.ArrayList] or javaList.to[mutable.List].

  8. I have .tryTo also which wraps the .to in a Try e.g. string.tryTo[Int]

I propose building this special converter into the Scala language (needs to be in language or atleast macro-land to support HKT-to-HKT cleanly) and making .to the only way to summon an implicit def.

1 Like

Twitter bijection does the same thing without using implicit conversions (defining Injection and Bijection typeclasses)


This is cool but the main disadvantage is no autocompletion in IDEs. It might be possible to add support for it but it might be weird. How do I look at the list of all possible types I can convert to?

1 Like

Aren’t they determined by what is imported in the current context? Exactly as IDEs support methods addition via implicit conversion.

IDEs offer autocompletion for method names, but not for generic parameters.