Impossible d'utiliser un générique sur la méthode unapply
d'un extracteur avec un "convertisseur" implicite pour prendre en charge une correspondance de modèle spécifique au type paramétré?Un «extracteur» Scala peut-il utiliser des génériques en cas d'inapplication?
Je voudrais faire (Notez l'utilisation de [T]
sur la ligne unapply
),
trait StringDecoder[A] {
def fromString(string: String): Option[A]
}
object ExampleExtractor {
def unapply[T](a: String)(implicit evidence: StringDecoder[T]): Option[T] = {
evidence.fromString(a)
}
}
object Example extends App {
implicit val stringDecoder = new StringDecoder[String] {
def fromString(string: String): Option[String] = Some(string)
}
implicit val intDecoder = new StringDecoder[Int] {
def fromString(string: String): Option[Int] = Some(string.charAt(0).toInt)
}
val result = "hello" match {
case ExampleExtractor[String](x) => x // <- type hint barfs
}
println(result)
}
Mais je reçois l'erreur compilation suivante
Error: (25, 10) not found: type ExampleExtractor case ExampleExtractor[String] (x) => x ^
Cela fonctionne très bien si je n'ai qu'une seule val
implicite dans la portée et que je supprime l'indice de type (voir ci-dessous), mais cela détruit l'objet.
object Example extends App {
implicit val intDecoder = new StringDecoder[Int] {
def fromString(string: String): Option[Int] = Some(string.charAt(0).toInt)
}
val result = "hello" match {
case ExampleExtractor(x) => x
}
println(result)
}
Je ne pense pas que ce soit possible pour le moment, voir [SI-884] (https://issues.scala-lang.org/browse/SI-884). –