1

I want to use an abstract type Value constrained to belong to the type class Show from cats.

My first attempt would be something like:

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

}

But the compiler doesn't find the implicit parameter Show[Value].

I know that I can define the previous example as:

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

However, I wanted to know if it is possible to use abstract types instead of type parameters.

4

1 回答 1

5

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

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

但是您的课程更直接的翻译UsingShow2如下:

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

  def showValues(values: List[Value]): String =
    values.map(showValue.show).mkString
}

基本上,由于您已将类型参数 Value换成抽象类型成员,因此您还必须将隐式参数换成隐式抽象成员showValue在我的示例中)。

于 2016-08-12T08:54:24.720 回答