Scala 使用类型类模式从基trait返回子类型

Scala 使用类型类模式从基trait返回子类型,scala,Scala,我有以下资料: trait Grabber[A, B] { def name: String def grab(a: A): Option[B] } object Grabber { implicit def toBooleanGrabber[A](s: String, f: A => Option[Boolean]) = new BooleanGrabber[A] { override val name: String = s overrid

我有以下资料:

trait Grabber[A, B] {
  def name: String
  def grab(a: A): Option[B]
}

object Grabber {
  implicit def toBooleanGrabber[A](s: String, f: A => Option[Boolean]) =
    new BooleanGrabber[A] {
      override val name: String = s
      override def grab(a: A): Option[Boolean] = f(a)
    }

  implicit def toDoubleGrabber[A](s: String, f: A => Option[Double]) =
    new DoubleGrabber[A] {
      override val name: String = s
      override def grab(a: A): Option[Double] = f(a)
    }

  implicit def toLongGrabber[A](s: String, f: A => Option[Long]) =
    new LongGrabber[A] {
      override val name: String = s
      override def grab(a: A): Option[Long] = f(a)
    }

  def apply[A, B](
    s: String, 
    f: A => Option[B]
  )(implicit ev: (String, A => Option[B]) => Grabber[A, B]): Grabber[A, B] =
    ev(s, f)
}

trait BooleanGrabber[A] extends Grabber[A, Boolean]
trait DoubleGrabber[A] extends Grabber[A, Double]
trait LongGrabber[A] extends Grabber[A, Long]

apply
方法工作正常,但是(根据其显式定义)它返回一个
抓取器[a,B]
。有没有办法更改
apply
方法的签名(希望是稍微更改一下)以返回
Grabber[a,B]
的子项?例如,使用
toBooleanGrabber
的调用理想情况下会返回
BooleanGrabber[T]
,而不是
Grabber[T,Boolean]

您可以向
apply
方法添加额外的类型参数

def apply[A, B, R](
  s: String, 
  f: A => Option[B]
)(implicit ev: (String, A => Option[B]) => R with Grabber[A, B]): R =
  ev(s, f)

您可以向
apply
方法添加额外的类型参数

def apply[A, B, R](
  s: String, 
  f: A => Option[B]
)(implicit ev: (String, A => Option[B]) => R with Grabber[A, B]): R =
  ev(s, f)

请问您为什么需要混凝土类型?也就是说,你把它抽象出来是有原因的,但是现在你需要知道底层的类型,哪种类型违背了我所想的目的。我可以问你为什么需要具体的类型吗?也就是说,你把它抽象出来是有原因的,但现在你需要知道底层类型,我认为它有违我的目的。
R也有可能,但我认为不太可靠,因为在隐式搜索过程中不考虑类型参数边界。太美了!(还有,隐式搜索期间边界的有趣之处。)也可以同时使用
R,但我认为不太可靠,因为隐式搜索期间不考虑类型参数边界。很漂亮!(另外,隐式搜索期间边界的有趣之处)您可以同时使用