2014-11-02 47 views
1

隱式轉換下面的代碼不會編譯:Scala中從Array [T]至IndexedSeq [T]

implicit class indexedSeqWithBinarySearch[T](xs: IndexedSeq[T]) { 
    def binarySearch(a: T) = ??? 
    } 

    Array(0, 1, 2).binarySearch(1) 

方法binarySearch不被添加到Array類。但是我猜想有一個來自Array[T] -> WrappedArray[T] -> mutable.IndexedSeq[T] -> collection.IndexedSeq[T]的隱式轉換鏈?如何製作ArrayIndexedSeq

+0

一種選擇是從你的特定集合類型定義轉換使用;這樣你也不依賴繼承(即子類型多態)。 – 2014-11-02 20:40:51

+0

是的,但爲什麼'Array's不能轉換爲'IndexedSeq's? – 2014-11-02 20:44:05

+0

它可以,但是在呼叫簽名中的'x:X''意味着'x'必須是'X'的實際子類型的一個實例,不能轉換爲'X';看到我的答案爲解決方案。 – 2014-11-02 22:25:02

回答

1

Array不是IndexedSeq的子類型,但是您的隱式類定義必須滿足這種情況。相反,您需要使用可見的任何類型,如IndexedSeq[T]

我使用myTail這裏一個更現實的例子:

implicit class indexedSeqWithBinarySearch[T, LS <% IndexedSeq[T]](xs: LS) { 
    def myTail = { 
    val xs1 = xs: IndexedSeq[T] // now the cast works 
    xs1.tail 
    } 
} 

println(Array(1, 2, 3).myTail) 

演員,因爲在簽名約束,且LS <% IndexedSeq[T]鑑於xs: IndexedSeq[T]作品。

A <% B指定A必須是可視作爲B,所以需要有從A在調用位置轉換到B範圍內,並且該轉換是在該方法的體效應。


更新:沒有關於將要棄用的視圖邊界,隱含的類聲明如下所示:

implicit class indexedSeqWithBinarySearch[T, LS](xs: LS)(implicit ls2ixseq: LS => IndexedSeq[T]) { 
    ... 
} 
+2

請注意''%'將被棄用。 http://jatinpuri.com/2014/03/replace-view-bounds/ – 2014-11-03 06:57:44

+0

這很瞭解:)我會在某些時候更新答案。 – 2014-11-03 15:07:06

相關問題