我能不能在提取器的unapply
方法上使用一个通用类型和一个隐式“转换器”来支持针对参数化类型的特定模式匹配呢?
我想做到这一点(请注意unapply
行中使用了[T]
),
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 ^
如果我只有一个隐式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)
}