Tob*_*oby 15 generics scala unapply extractor
我不能在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)
}
Run Code Online (Sandbox Code Playgroud)
但是我得到以下编译错误
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)
}
Run Code Online (Sandbox Code Playgroud)
您的类型化字符串解码器的一个变体看起来很有前途:
trait StringDecoder[A] {
def fromString(s: String): Option[A]
}
class ExampleExtractor[T](ev: StringDecoder[T]) {
def unapply(s: String) = ev.fromString(s)
}
object ExampleExtractor {
def apply[A](implicit ev: StringDecoder[A]) = new ExampleExtractor(ev)
}
Run Code Online (Sandbox Code Playgroud)
然后
implicit val intDecoder = new StringDecoder[Int] {
def fromString(s: String) = scala.util.Try {
Integer.parseInt(s)
}.toOption
}
val asInt = ExampleExtractor[Int]
val asInt(Nb) = "1111"
Run Code Online (Sandbox Code Playgroud)
似乎产生了你所要求的。仍然存在一个问题:似乎试图
val ExampleExtractor[Int](nB) = "1111"
Run Code Online (Sandbox Code Playgroud)
导致编译器崩溃(至少在我的 2.10.3 SBT Scala 控制台内)。
| 归档时间: |
|
| 查看次数: |
267 次 |
| 最近记录: |