使用许多类型参数键入 Class

Type Class with many type parameters

我有几个类型参数的函数。如何告诉编译器这些类型实际上是类型 class?

trait Sizeable[-T, +R] {
  def mySize(x: T): R
}

implicit object StringSize extends Sizeable[String, Int] {
  def mySize(s: String) = s.length
}

def sum[T, R: Sizeable[T, R]](xs: List[T]): R =  xs.map(x => x.mySize)

错误是:

Error:(9, 14) A$A40.this.Sizeable[T,R] does not take type parameters 
def sum[T, R: Sizeable[T, R]](xs: List[T]): R =  xs.map(x => x.mySize);}

在这种情况下,您不能使用上下文绑定。您必须显式编写隐式参数:

def foo[T, R](xs: List[T])(implicit sizeable: Sizeable[T,R]): List[R] =
  xs.map(x => sizeable.mySize(x))