类型不匹配; 发现:Int(1)要求:B

Ele*_*fee 4 generics scala type-mismatch enrich-my-library

我正在尝试扩展List该类,以便为比较大小提供一些更简化的方法,但是我遇到了标题中的错误...

这是我的代码:

implicit class RichList[A, B](input: List[A]) {
  def >(that: List[B]): Boolean = input.size > that.size
  def <(that: List[B]): Boolean = input.size < that.size
}
Run Code Online (Sandbox Code Playgroud)

这个想法是因为它只是比较了列表的大小,它们的类型可能不同而且无关紧要,但是当我尝试这样做时:

val test = List(1,2,3,4) < List(1,2,3,4,5)
Run Code Online (Sandbox Code Playgroud)

我得到了前面提到的错误.如果我删除B并设置that为类型List[A]它工作正常,但然后我将无法使用包含2种不同类型的列表...

为什么A和B都不能是同一类型?或者我错过了什么?

编辑:好的我找到了错误的解决方案,这很简单:

implicit class RichList[A](input: List[A]) {
  def >[B](that: List[B]): Boolean = input.size > that.size
  def <[B](that: List[B]): Boolean = input.size < that.size
}
Run Code Online (Sandbox Code Playgroud)

但是我的问题仍然存在; 为什么我不能这样做呢?

tir*_*ran 6

在助手类中,您可以B在类初始化中定义类型.但是这种类型在方法><用法之前是未知的.

我的解决方案就是这样.

implicit class RichList[A](input: List[A]) {
  def >[B](that: List[B]): Boolean = input.size > that.size
  def <[B](that: List[B]): Boolean = input.size < that.size
}
Run Code Online (Sandbox Code Playgroud)

编辑

既然你问过为什么不可能用其他方式,请考虑以下示例.

List(1,2,3) > List("1", "2")
Run Code Online (Sandbox Code Playgroud)

我们希望这会隐含地扩展到(这不会发生)

new RichList[Int, B](List[Int](1,2,3)).>(List[String]("1", "2"))
Run Code Online (Sandbox Code Playgroud)

但是,类型B没有解决String.因此,编译器忽略此隐式转换,并给出编译错误.