Resolving Implicit for `Show` Typeclass Instance

不打扰是莪最后的温柔 提交于 2019-12-06 02:44:22

This isn't really how type classes work. Instead of extending the type class in your class definition, you provide an instance for your type separately as an implicit value:

import scalaz._, Scalaz._

trait Gender
case object Male extends Gender
case object Female extends Gender

implicit val GenderShows: Show[Gender] = Show.shows {
  case Male   => "Male"
  case Female => "Female"
}

def f[A: Show](x: A): String = implicitly[Show[A]].shows(x)

And then:

scala> val male: Gender = Male
male: Gender = Male

scala> f(male)
res0: String = Male

This is one of the big advantages of type classes over subtyping—they decouple the definition of your data types from the definition of the operations you want to support on those types (nobody wants to have to change their inheritance hierarchy every time they need to support a new serialization library, for example).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!