Implicit conversion for generic type?

Given this function:

def justTrue[T, S](seq: S)(implicit ev: S <:< Seq[T]) = true justTrue(List(1,2,3)) >> true 

It works. But why can't you use the same signature as an implicit conversion?

 implicit class TruthTeller[T, S](seq: S)(implicit ev: S <:< Seq[T]) { def justTrue = true } List(1,2,3).justTrue >> error: Cannot prove that List[Int] <:< Seq[T]. 

Is implicit conversion just a function?

+7
scala implicit conversion
source share
2 answers

You are absolutely right, this should work just as well in implicit def / class .

This is an error in which the type parameter accidentally saves the type inference from the implicit representation parameter:

SI-7944: type variables go wild

Now it is fixed with 2.11.0-M7:

 Welcome to Scala version 2.11.0-M7 (OpenJDK 64-Bit Server VM, Java 1.7.0_45). Type in expressions to have them evaluated. Type :help for more information. scala> :pa // Entering paste mode (ctrl-D to finish) implicit class TruthTeller[T, S](seq: S)(implicit ev: S <:< Seq[T]) { def justTrue = true } List(1,2,3).justTrue // Exiting paste mode, now interpreting. defined class TruthTeller res0: Boolean = true 

As for the workarounds, there are many of them, you can use a higher level, as in your answer, or, for example, force the conclusion of T from the parameter seq :

 // the implicit ev isn't even needed here anymore // but I am assuming the real use case is more complex implicit class TruthTeller[T, S](seq: S with Seq[T])(implicit ev: S <:< Seq[T]) { def justTrue = true } // S will be inferred as List[Int], and T as Int List(1,2,3).justTrue 
+6
source share

The best solution I found yet:

 import scala.language.higherKinds implicit class TruthTeller[T, S[T] <: Seq[T]](seq: S[T]) { def justTrue = true } List(1,2,3).justTrue >> true 

But I really want to know why the source code is not working.

0
source share

All Articles