gpt4 book ai didi

scala - Scala "extractor"可以在 unapply 上使用泛型吗?

转载 作者:行者123 更新时间:2023-12-03 20:57:24 26 4
gpt4 key购买 nike

我不能在 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)
}

最佳答案

类型字符串解码器的一个变体看起来很有希望:

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)
}

然后
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"

似乎产生了你所要求的。一个问题仍然存在:似乎试图
val ExampleExtractor[Int](nB) = "1111"

导致编译器崩溃(至少在我的 2.10.3 SBT Scala 控制台内)。

关于scala - Scala "extractor"可以在 unapply 上使用泛型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31746392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com