Matching on type patterns with type variables and type classes

129 views Asked by At

This question is still unanswered despite of it was marked as duplicate.

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

Suppose I have a type class:

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 typed class which uses my type class

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

When I try to typify 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 is wrong in this case of the usage of a type parameter in the pattern matching?

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

0

There are 0 answers