在Scala中使用带有类型类的抽象类型

Lab*_*bra 1 scala scala-cats

我想用一个抽象类型Value的限制属于类型类Show猫科动物.

我的第一次尝试将是这样的:

package examples
import cats._
import cats.data._
import cats.implicits._

class UsingShow1 {
  type Value <: Show[Value]  // Not sure if this declaration is right

  def showValues(vs: List[Value]): String = 
    vs.map(implicitly[Show[Value]].show(_)).mkString // Error line

}
Run Code Online (Sandbox Code Playgroud)

但是编译器没有找到隐含参数Show[Value].

我知道我可以将前面的例子定义为:

class UsingShow2[Value: Show] {
  def showValues(vs: List[Value]): String = 
    vs.map(implicitly[Show[Value]].show(_)).mkString
}
Run Code Online (Sandbox Code Playgroud)

但是,我想知道是否可以使用抽象类型而不是类型参数.

Jul*_*Foy 5

只需Show[Value]像往常一样在使用站点添加类型的隐式参数:

class UsingShow1 {
  type Value
  def showValues(values: List[Value])(implicit showValue: Show[Value]): String =
    values.map(showValue.show).mkString
}
Run Code Online (Sandbox Code Playgroud)

但是,对您的UsingShow2课程进行更直接的翻译如下:

class UsingShow1 {
  type Value
  implicit def showValue: Show[Value]

  def showValues(values: List[Value]): String =
    values.map(showValue.show).mkString
}
Run Code Online (Sandbox Code Playgroud)

基本上,由于您已经为抽象类型成员交换了类型参数 ,因此您还必须为隐式抽象成员交换隐式参数(在我的示例中).ValueshowValue