0

Let's say I have a type class

trait CanMeow[T] {
    def meow(t:T):String
}

Now I have a different type class

trait IsCatEquivalent[T] {
    def makeSound(t:T):String
    def isAlive(t:T):Boolean
}

And now I want to make every CatEquivalent member of CanMeow type class. What I can do is

implicit def catEquivalentCanMeow[T](implicit ce:IsCatEquivalent[T]) = new CanMeow[T] {
    def meow(t:T) = ce.makeSound(t)
}

How does this affect performance? From the looks of it every time a method is called with implicit parameter of type CanMeow[T] a new object is constructed. Is it so? And if, is this cheap enough that it is not worth caching the instances?

Other question: is there a better way to do this? (Making one type class extend the other may not be an option, for example if they come from different libraries)

Martin Kolinek
  • 2,010
  • 14
  • 16

1 Answers1

4

To compare the performance impact of implicit conversion and its alternatives, see this article. This question contains another microbenchmark.

Community
  • 1
  • 1
thSoft
  • 21,755
  • 5
  • 88
  • 103