【问题标题】:Type Parameter in Case Class Using Trait w/ Implicits使用带有隐式特征的案例类中的类型参数
【发布时间】:2017-04-15 11:55:55
【问题描述】:

假设我们有一个特质:

trait ThingToThing[-A, +B] { def apply(a: A): B }

及其伴随对象:

object ThingToThing {
  implicit object StringToBoolean extends ThingToThing[String, Boolean] {
    override def apply(a: String): Boolean = a.toBoolean
  }
}

还有一个案例类:

case class Thing[A](a: A) {
  def to[B](implicit thing: ThingToThing[A, B]): B = thing(a)
}

这允许我执行以下操作:

Thing("true").to[Boolean]
res0: Boolean = true

这一切都很好,我可以这样做:

case class MyClass(ss: Seq[String]) {
  def doStuff(s: String) = Thing(s).to[Boolean]
}

但是,我想做的是:

case class MyClass[B](ss: Seq[String]) {
  def doStuff(s: String) = Thing(s).to[B]
}

但是,这个错误:

error: could not find implicit value for parameter thing: ThingToThing[String,B]

有没有办法可以在我的MyClass 中使用类型参数?

** 不要沉迷于将字符串转换为布尔值的玩具示例;我只是用这个作为一个简单的例子来说明问题。

【问题讨论】:

    标签: scala


    【解决方案1】:

    编译器在调用站点Thing(s).to[B] 中找不到ThingToThing[String,B] 的隐式实例(B 未知):

    case class MyClass[B](ss: Seq[String]) {
      def doStuff(s: String) = Thing(s).to[B]
    }
    

    因此错误。

    您可以在构造函数中声明所需的隐式以使其在对象创建的调用站点中解析(当B 已知时):

    case class MyClass[B](ss: Seq[String])(implicit t2t: ThingToThing[String, B]) {
      def doStuff(s: String) = Thing(s).to[B]
    }
    

    ,或者在方法中声明它以使其在方法调用的调用站点中解析(当B已知时):

    case class MyClass[B](ss: Seq[String]) {
      def doStuff(s: String)(implicit t2t: ThingToThing[String, B]) = Thing(s).to[B]
    }
    

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2020-10-27
    • 1970-01-01
    • 2018-04-11
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多