scala – 类型不匹配;发现:Int(1)要求:B
发布时间:2020-12-16 18:12:38 所属栏目:安全 来源:网络整理
导读:我正在尝试扩展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
我正在尝试扩展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,4,5) 我得到了前面提到的错误.如果我删除B并将其设置为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 } 不过我的问题仍然存在;为什么我不能这样做呢? 解决方法
在您的助手类中,您在类初始化中定义类型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 } 编辑 既然你问过为什么不可能用其他方式,请考虑以下示例. List(1,3) > List("1","2") 我们希望这会隐含地扩展到(这不会发生) new RichList[Int,B](List[Int](1,3)).>(List[String]("1","2")) 但是,类型B未解析为String.因此,编译器忽略此隐式转换,并给出编译错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |