Created
November 18, 2011 14:22
-
-
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
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
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