Matching Type Templates with Type Variables and Class Types

This question still remains unanswered, although it has been marked as a duplicate.

From http://www.scala-lang.org/files/archive/spec/2.12/08-pattern-matching.html#type-patterns we can write the following code

Suppose I have a class like:

trait T[A] { def getType: String } object T { def apply[A](implicit t: T[A]): T[A] = t implicit object TInt extends T[Int] { def getType = "Int" } implicit object TString extends T[String] { def getType = "String" } } 

and a typed class that uses a type class

 class C[A] { def func(implicit t: T[A]) = t.getType } 

When I try to type C[A] , I get an error

 val list: List[Int] = 1 :: 2 :: Nil val result = list match { case list: List[t] => new C[t] //type parameter 't' } result.func //Error: could not find implicit value for parameter t: T[t] 

What, in this case, is the incorrect use of the type parameter in comparison with the pattern?

Updated Another simple example:

 val array = List[Int](1, 2, 3, 4) match { case l: List[a] => scala.collection.mutable.ArrayBuffer[a]() } array += 1 

Error: type mismatch; found: Int(1), required: a array += 1 type mismatch; found: Int(1), required: a array += 1

+5
source share

Source: https://habr.com/ru/post/1261433/


All Articles