我不能在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 ^
如果我只有一个隐式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)
}