假设我有一个类型类
trait CanMeow[T] {
def meow(t:T):String
}
现在我有一个不同的类型类
trait IsCatEquivalent[T] {
def makeSound(t:T):String
def isAlive(t:T):Boolean
}
现在我想让 CanMeow 类型类的每个 CatEquivalent 成员。我能做的是
implicit def catEquivalentCanMeow[T](implicit ce:IsCatEquivalent[T]) = new CanMeow[T] {
def meow(t:T) = ce.makeSound(t)
}
这对性能有何影响?从外观上看,每次使用 CanMeow[T] 类型的隐式参数调用方法时,都会构造一个新对象。是这样吗?如果,这是否足够便宜以至于不值得缓存实例?
其他问题:有没有更好的方法来做到这一点?(使一个类型类扩展另一个可能不是一种选择,例如,如果它们来自不同的库)