3

I'm trying to implement simple type class pattern. It suppose to work similarly to scalaz's typeclasses. Unfortunately I can't get it to work. I have trait Str

trait Str[T] {
  def str(t: T): String
}

object Str {
  def apply[T](implicit instance: Str[T]) : Str[T] = instance
}

And in my and implicit instance of it.

object Temp extends App {

  implicit val intStr = new Str[Int] {
    def str(i: Int) = i.toString
  }

  1.str //error: value str is not a member of Int

}

I would appreciate any insight.

1
  • Shouldn't it be Str(1).str? You were not defining an implicit class, just an object with apply. Commented Apr 18, 2016 at 16:45

1 Answer 1

8

Everything you can do now is

Str[Int].str(1)

to use 1.str you need to introduce implicit conversion.

You can for example use this approach:

implicit class StrOps[A](val self: A) extends AnyVal {
    def str(implicit S: Str[A]) = S.str(self)
}

Which gives:

scala> 1.str
res2: String = 1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.