我有几个类型参数的功能。如何告诉编译器这些类型实际上是类型类?
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);}
答案 0 :(得分:3)
在这种情况下,您无法使用上下文绑定。您必须明确地编写隐式参数:
def foo[T, R](xs: List[T])(implicit sizeable: Sizeable[T,R]): List[R] =
xs.map(x => sizeable.mySize(x))