Yann Moisan
Yann Moisan

Reputation: 8281

What is the simplest typeclass example

I want to implement the simplest typeclass example.

Here I come : my typeclass is just a regular scala trait

scala> trait Show[A] { def show(a: A) : String }
defined trait Show

Here is an instance of my typeclass for type Int

scala> implicit val IntShow = new Show[Int] { def show(i: Int) = s"'$i' is an int" }
IntShow: Show[Int] = $anon$1@14459d53

Here is a client code that uses my typeclass

scala> def f[A](a:A)(implicit s : Show[A]) = println(s.show(a))
f: [A](a: A)(implicit s: Show[A])Unit

Let's call it

scala> f(1)
'1' is an int

Could it be simpler ?

Upvotes: 1

Views: 259

Answers (1)

Chris Martin
Chris Martin

Reputation: 30736

Sure - you can remove the method.

scala> trait Show[A]
defined trait Show

scala> implicit object IntShow extends Show[Int]
defined object IntShow

You can also clean up the usage code a bit by using a context bound instead of an implicit parameter.

scala> def f[A : Show](a: A) = a
f: [A](a: A)(implicit evidence$1: Show[A])A

Example calls (to demonstrate that this type class has at least some effect):

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")
               ^

Upvotes: 7

Related Questions