定义它接受类型的方法:列表[_ <:AnyVal]错误消息发送到值类
def foo(x : List[_ <: AnyVal]) = x
尝试使用AnyRef:
foo(List(new Test))
error: type mismatch;
found : Test
required: AnyVal
Note that implicit conversions are not applicable because they are ambiguous:
both method ArrowAssoc in object Predef of type [A](self: A)ArrowAssoc[A]
and method Ensuring in object Predef of type [A](self: A)Ensuring[A]
are possible conversion functions from Test to AnyVal
问题1:在警告消息,为什么编译器忽略Predef.scala中定义的其他两个“通用到AnyVal”隐式转换?
final implicit class StringFormat[A] extends AnyVal
final implicit class any2stringadd[A] extends AnyVal
删除以前的模糊性,并迫使编译器使用ArrowAssoc隐式转换:
foo(List(new Test -> 1))
error: the result type of an implicit conversion must be more specific than AnyVal
问题2:这是什么错误消息,其暗示?它令人困惑。 ArrowAssoc类中的方法def -> [B](y: B): Tuple2[A, B] = Tuple2(self, y)
返回AnyRef类型的Tuple2。所以,一个更有用的错误信息可能是found Tuple2 required AnyVal
?
谢谢Jatin。所以,混淆是错误信息的不一致。在一种情况下'注意隐式转换是不适用的。'&另一种'隐式转换的结果类型必须比AnyVal更具体'这两种错误信息都是因为碰撞问题相同吗? – Samar
是的。这是相同的问题相同的错误。第二种说法只是对第一种说法的补充说明。 – Jatin
我还有一个问题:当编译器看到'foo(List(new Test - > 1))'时,它会尝试评估'new Test - > 1'来看它是否是AnyVal。因此,它执行以下步骤:它找到一个具有 - >定义的隐式类,并且具有 - > defined的唯一隐式范围是ArrowAssoc类。那么,这里应该没有歧义? – Samar