【问题标题】:Type mismatch; found : Int(1) required: B类型不匹配;找到:需要 Int(1):B
【发布时间】:2014-04-07 09:53:19
【问题描述】:

我正在尝试扩展 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
}

我的想法是,由于它所做的只是比较列表的大小,它们的类型可能不同并且没关系,但是当我尝试这样做时:

val test = List(1,2,3,4) < List(1,2,3,4,5)

我得到了前面提到的错误。如果我删除 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
}

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

【问题讨论】:

  • 你也可以使用这个:def &gt;(that: List[_]): .... 因为你不关心实际类型
  • 这实际上可能是个好主意......奇怪我怎么没想到

标签: scala generics type-mismatch enrich-my-library


【解决方案1】:

在您的帮助类中,您在类初始化中定义类型B。但是这种类型在使用 &gt;&lt; 方法之前是未知的。

我的解决方案是这样的。

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
}

编辑

既然你问了,为什么它不可能以其他方式,请考虑以下示例。

List(1,2,3) > List("1", "2")

我们希望这会隐式扩展到(这不会发生

new RichList[Int, B](List[Int](1,2,3)).>(List[String]("1", "2"))

但是,类型 B 未解析为 String。因此,编译器忽略了这种隐式转换,并给出了编译错误。

【讨论】:

  • 有趣,我们同时添加了相同的解决方案
猜你喜欢
  • 2014-09-26
  • 2015-04-03
  • 1970-01-01
  • 2019-04-30
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多