gpt4 book ai didi

scala - 使用带有隐含的特征的案例类中的类型参数

转载 作者:行者123 更新时间:2023-12-05 00:52:00 30 4
gpt4 key购买 nike

假设我们有一个特征:

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 中使用类型参数? ?

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

最佳答案

编译器找不到 ThingToThing[String,B] 的隐式实例( B 未知)在调用站点 Thing(s).to[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]
}

关于scala - 使用带有隐含的特征的案例类中的类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43420930/

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