パラメーター化された型に固有のパターン マッチをサポートするために、エクストラクターのメソッドでジェネリックをunapply
暗黙的な「コンバーター」と共に使用することはできませんか?
私はこれをしたいです(行での使用に注意してください[T]
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)
}
しかし、次のコンパイルエラーが発生します
Error: (25, 10) not found: type ExampleExtractor case ExampleExtractor[String] (x) => x ^
スコープ内に1 つだけ暗黙的val
であり、型ヒント (以下を参照) をドロップすると問題なく動作しますが、それではオブジェクトが無効になります。
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)
}