Skip to content

Instantly share code, notes, and snippets.

@admackin
Last active December 18, 2015 04:48
Show Gist options
  • Save admackin/5727567 to your computer and use it in GitHub Desktop.
Save admackin/5727567 to your computer and use it in GitHub Desktop.
Implicit conversion for Traversable instances where the elements are convertible. Scala implicit conversions are handy (if controversial). But when methods return pre-constructed collections of a type, the implicit conversion won't work - see http://stackoverflow.com/questions/8935811/scala-implicit-conversion-of-a-generic-argument?rq=1 This so…
/** Implicit conversion for Traversable instances where the elements are convertible - possibly controversial */
implicit def convTrav[S, T, I[S] <: Traversable[S]](input: I[S])(implicit c: S => T): I[T] =
(input map c).asInstanceOf[I[T]]
/** Less controversial version of the above using the pimp-my-library pattern
- to use this, you must explicitly call .as[TypeName] on the source Traversable */
trait Convertible[M[A], A] {
def as[B](implicit f: A => B): M[B]
}
implicit def travToConvertible[A, M[A] <: Traversable[A]](xs: M[A]) = new Convertible[M, A] {
def as[B](implicit f: A => B) = (xs map f).asInstanceOf[M[B]]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment