2016-09-23 144 views
0

定义它接受类型的方法:列表[_ <: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

回答

2

先回答你的第二个问题。试试这个:

class Temp 

implicit class Arrow[T](a:T) extends Temp{ 
    def -->[B](b:B) = (a,b) 
} 
def foo(x : List[_ <: Temp]) = x 

scala>  foo(List(1 --> 2)) 
res0: List[Temp] = List([email protected]) 

这个按预期工作。它并不抱怨,因为它正在搜索Temp而不是Tuple2。 现在引入歧义:

implicit class OtherTemp[T](a:T) extends Temp{} 
foo(List(1 --> 2)) //compile error 

它抱怨碰撞失败。所以要回答你的问题,为什么它没有显示AnyRef是因为:

还记得ArrowAssoc被调用来获得AnyVal表示。与->,它有一个Tuple2,并试图检索AnyVal。由于无法检索AnyVal,因此无法将其转换为AnyVal,因此将其标记为错误。它的真实身份是无关紧要的。

对于第一个问题: 在我的理解中,implicits作为第一个搜索基础。所以一旦发现两个并且含糊不清,它就会停止抱怨。可能这就是为什么它不与StringFormat尝试等,这可以通过REPL重新排序隐含为了确认

implicit class OtherTemp2[T](a:T) extends Temp{ 
} 
implicit class OtherTemp[T](a:T) extends Temp{ 
} 

foo(List[Temp]("asdf")) 

编译器会为ArrowOtherTemp2的碰撞。如果您重新排序并再次运行repl,则会根据先找到哪个隐式进行投诉。 但我无法找到证实此事的官方消息。

+0

谢谢Jatin。所以,混淆是错误信息的不一致。在一种情况下'注意隐式转换是不适用的。'&另一种'隐式转换的结果类型必须比AnyVal更具体'这两种错误信息都是因为碰撞问题相同吗? – Samar

+0

是的。这是相同的问题相同的错误。第二种说法只是对第一种说法的补充说明。 – Jatin

+0

我还有一个问题:当编译器看到'foo(List(new Test - > 1))'时,它会尝试评估'new Test - > 1'来看它是否是AnyVal。因此,它执行以下步骤:它找到一个具有 - >定义的隐式类,并且具有 - > defined的唯一隐式范围是ArrowAssoc类。那么,这里应该没有歧义? – Samar