我正试图为以下结构编写一个通用的隐式实例:
object SmartHasher {
trait GetSmartHash[T] {
def calculateHash(value: T): Int
}
object syntax {
implicit class GetHashOps[T: GetSmartHash](itemToBeHashed: T) {
def hashItSmartway(implicit GetSmartHashInstance: GetSmartHash[T]): Int =
GetSmartHashInstance.calculateHash(itemToBeHashed)
}
}
object instances {
import syntax._
implicit def stringSmartHash: GetSmartHash[String] = (s: String) =>s.size % 10 // smart demo thing :D
}
现在我正试图定义一个通用的隐式实例,它适用于任何Vector、List或Array
其中定义了其元素的smarthash方法:
我应该用什么类型来代替Seq,因为我试着用它,但它不起作用
implicit def sequenceHash[T: GetSmartHash]: GetSmartHash[Seq[T]] =
(sequence: Seq[T]) => sequence.map(element => element.hashItSmartway).product
如果我为Vector:这样的精确集合定义它
implicit def sequenceHash[T: GetSmartHash]: GetSmartHash[Vector[T]] =
(sequence: Vector[T]) => sequence.map(element => element.hashItSmartway).product
然后它就如我所期望的那样工作了。有没有建议用通用的方式为这3个集合写这篇文章,以防止重复类似的代码3次?当做
尝试
object instances {
import syntax._
// stringSmartHash ...
implicit def sequenceHash[Col[X] <: Iterable[X], T: GetSmartHash]: GetSmartHash[Col[T]] =
(sequence: Col[T]) => sequence.map(element => element.hashItSmartway).product
}
测试:
import instances._, syntax._
List("aa", "bbb").hashItSmartway //6
Seq("aa", "bbb").hashItSmartway //6
Vector("aa", "bbb").hashItSmartway //6
如果您希望sequenceHash
也适用于Array
,请将上界替换为视图绑定
implicit def sequenceHash[Col[_], T: GetSmartHash](implicit ev: Col[T] => Iterable[T]): GetSmartHash[Col[T]] =
(sequence: Col[T]) => sequence.map(element => element.hashItSmartway).product