Skip to content

Instantly share code, notes, and snippets.

@szeiger
Created November 18, 2011 14:22
Show Gist options
  • Save szeiger/1376569 to your computer and use it in GitHub Desktop.
Save szeiger/1376569 to your computer and use it in GitHub Desktop.
Using an extra object to infer one of two type parameters of a method
object ToTest extends App {
val i1 = new Invoker(List(1,2,3,1))
val t1 = i1.to[Set]()
val t1t: Set[Int] = t1
println(t1)
val i2 = new Invoker(Seq("a","b"))
val t2 = i2.to[Array]()
val t2t: Array[String] = t2
println(t2)
}
class Invoker[+R](val contents: Traversable[R]) {
import scala.collection.generic.CanBuildFrom
final def build[To](implicit canBuildFrom: CanBuildFrom[Nothing, R, To]): To = {
val b = canBuildFrom()
contents.foreach { x => b += x }
b.result()
}
final def to[C[_]] = new To[C]()
final class To[C[_]] private[Invoker] () {
def apply[RR >: R]()(implicit canBuildFrom: CanBuildFrom[Nothing, RR, C[RR]]) =
build[C[RR]](canBuildFrom)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment