本文介绍了为SeqLike创建扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我要扩展 SeqLike 的功能:

import collection.SeqLike

implicit class Test[A, Repr <: SeqLike[A, Repr]](val sq: Repr) extends AnyVal {
  def foo(): Repr = sq
}

然后这不起作用:

Vector(1, 2, 3).foo()

也不是:

new Test(Vector(1, 2, 3)).foo()

<console>:41: error: inferred type arguments
                    [Nothing,scala.collection.immutable.Vector[Int]] 
                    do not conform to class Test's type parameter bounds 
                    [A,Repr <: scala.collection.SeqLike[A,Repr]]
              new Test(Vector(1, 2, 3)).foo()
              ^

只有这样才有效:

new Test[Int, Vector[Int]](Vector(1, 2, 3)).foo()

如何使隐式类工作?

推荐答案

sq 键入 SeqLike 而不是类型参数。这将允许编译器有一些坚定的依据,然后可以推断 Repr
现在唯一明显的问题是,我们将在 foo 中有一个类型不匹配,因为它应该返回一个 Repr ,但我们返回 SeqLike [A,Repr]

Just have sq be typed as a SeqLike instead of a type parameter. This will allow the compiler to have some firm ground on which to rely, from which Repr can then be inferred.The only apparent problem now would be that we're going to have a type mismatch in foo, as it is supposed to return a Repr but we return a SeqLike[A, Repr].

简单,使用 repr 方法:

implicit class Test[A, Repr](val sq: SeqLike[A, Repr]) extends AnyVal {
  def foo(): Repr = sq.repr
}
Vector(1, 2, 3).foo()

这篇关于为SeqLike创建扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:44