Last active
December 18, 2015 04:48
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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