【问题标题】:Using abstract types with type classes in Scala在 Scala 中使用抽象类型和类型类
【发布时间】:2016-08-12 19:23:11
【问题描述】:

我想使用一个抽象类型 Value 被限制为属于来自 cats 的类型类 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

}

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

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

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

但是,我想知道是否可以使用抽象类型代替类型参数。

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    像往常一样在使用站点添加一个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)。

    【讨论】:

    • 谢谢,第二种风格正是我想要的。我想在抽象类型声明中用一行来表达对Show 的约束Value。反正加implicit def showValue: Show[Value]也可以。
    猜你喜欢
    • 2018-05-03
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多