加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala“提取器”可以在未应用程序中使用泛型?

发布时间:2020-12-16 09:17:33 所属栏目:安全 来源:网络整理
导读:我不能在提取器的未应用方法上使用泛型以及隐式“转换器”来支持特定于参数化类型的模式匹配? 我想这样做(请注意在未应用行上使用[T]) trait StringDecoder[A] { def fromString(string: String): Option[A]}object ExampleExtractor { def unapply[T](a: S
我不能在提取器的未应用方法上使用泛型以及隐式“转换器”来支持特定于参数化类型的模式匹配?

我想这样做(请注意在未应用行上使用[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
^

如果我在范围中只有一个隐式值并放弃类型提示(见下文),那么它可以正常工作,但是会破坏该对象.

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控制台中).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读