After watching a youtube video with the title Scala Type Members vs Type Parameters. I wrote the following.
Purely Type parameter version works fine
trait Joiner[Elem,R] { def join(xs: Seq[Elem]): R } object Program { def doJoin[T,R] (xs: T *) (implicit j: Joiner[T,R] ): R = j.join (xs) def main(args: Array[String]): Unit = { implicit val charToStringJoiner = new Joiner[Char,String] { override def join(xs: Seq[Char]): String = xs.mkString("+") } implicit val charToInt = new Joiner[Char,Int] { override def join(xs: Seq[Char]): Int = xs.mkString.toInt } val s:String = doJoin[Char,String]('1','2') println(s) val n :Int = doJoin[Char,Int]('1','2') println(n) } }
Mixed Type Member & Parameter version -
trait Joiner[Elem] { type R def join(xs: Seq[Elem]): R } object Program { def doJoin[T] (xs: T *) (implicit j: Joiner[T] ): j.R = j.join (xs) def main(args: Array[String]): Unit = { implicit val charToStringJoiner = new Joiner[Char] { override type R = String override def join(xs: Seq[Char]): String = xs.mkString("+") } implicit val charToInt = new Joiner[Char] { override type R = Int override def join(xs: Seq[Char]): Int = xs.mkString.toInt } val s:String = doJoin('1','2') //doesn't work println(s) val n :Int = doJoin('1','2') //doesn't work println(n) } }
Version 1 is fine however version 2 doesn't compile. How can this be fixed while having both implicit in scope? Specifically how can I specify the return type which will help the compiler resolve the correct implicit