【发布时间】: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