2016-09-23 93 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