我想实现最简单的类型类示例.
我来了:我的类型类只是一个常规的scala特征
scala> trait Show[A] { def show(a: A) : String }
defined trait Show
Run Code Online (Sandbox Code Playgroud)
这是类型Int的类型类的实例
scala> implicit val IntShow = new Show[Int] { def show(i: Int) = s"'$i' is an int" }
IntShow: Show[Int] = $anon$1@14459d53
Run Code Online (Sandbox Code Playgroud)
这是一个使用我的类型类的客户端代码
scala> def f[A](a:A)(implicit s : Show[A]) = println(s.show(a))
f: [A](a: A)(implicit s: Show[A])Unit
Run Code Online (Sandbox Code Playgroud)
我们称之为
scala> f(1)
'1' is an int
Run Code Online (Sandbox Code Playgroud)
它会更简单吗?
当然 - 您可以删除该方法.
scala> trait Show[A]
defined trait Show
scala> implicit object IntShow extends Show[Int]
defined object IntShow
Run Code Online (Sandbox Code Playgroud)
您还可以使用上下文绑定而不是隐式参数来稍微清理使用代码.
scala> def f[A : Show](a: A) = a
f: [A](a: A)(implicit evidence$1: Show[A])A
Run Code Online (Sandbox Code Playgroud)
示例调用(以证明此类型类至少具有一些效果):
scala> f(3)
res0: Int = 3
scala> f("3")
<console>:11: error: could not find implicit value for
evidence parameter of type Show[String]
f("3")
^
Run Code Online (Sandbox Code Playgroud)