2013-10-12 26 views
1

我有一種算法可以對某些對象的索引序列進行操作:它獲取兩個這樣的序列並輸出一個結果序列。我想它能夠與至少工作:斯卡拉泛型:兩級數據結構中的協方差/相反性

  • 字符串中的字符
  • 線(串)在文本

爲了簡單起見陣列,讓我們假設這個算法只是構造一個新的對象序列,從每個原始序列中逐個獲取對象。當我不得不返回所需類型的對象或原始對象的空序列時,有一些特殊情況。只有兩個操作我將在原來的序列使用的都是:

  • 通過指數
  • 越來越序列的大小

我當前的代碼看起來像這樣得到個元素

class GenericTest[C, T <: IndexedSeq[C]](a: T, b: T) { 
    def run: T = { 
    // special case #1: need to return empty sequence here 
    if (a.size == 0) { 
     // what I've tried: 

     return new T() 
     // fails: "class type required but T found" 

     return Seq[C]() 
     // fails: "type mismatch; found : Seq[C] required: T" 

     return Array[C]() 
     // fails: "not enough arguments for method apply: (implicit 
     // evidence$2: scala.reflect.ClassTag[C])Array[C] in object 
     // Array. Unspecified value parameter evidence$2." 

     return Array.ofDim[C](0) 
     // fails: "No ClassTag available for C" 
     // "not enough arguments for method ofDim: (implicit 
     // evidence$3: scala.reflect.ClassTag[C])Array[C]. 
     // Unspecified value parameter evidence$3." 
    } 

    // special case #2: need to return original input here 
    if (a == b) { 
     return a 
     // it works 
    } 

    val result = new MutableList[C] 

    for (i <- 0 until scala.math.min(a.size, b.size)) { 
     result += a(i) 
     result += b(i) 
    } 

    // what I've tried: 

    return result 
    // fails: "type mismatch; found : result.type (with underlying 
    // type scala.collection.mutable.MutableList[C]) required: T" 

    return result.toIndexedSeq 
    // fails: "type mismatch; found : scala.collection.immutable.IndexedSeq[C] 
    // required: T" 
    } 
} 

所以,基本上,問題是 - 我該如何正確設置Scala仿製藥才能完成此任務:

0對象
  • 返回空序列
  • 返回構造的對象的序列
  • 返回原始輸入

我想這個問題,要求協方差/逆變註解類型,我的協方差福似乎是缺少...

回答

3

由於scala中的列表是協變的,只要它是列表類型的子類型,就可以將任何對象添加到列表中。

class GenericTest[C](a: IndexedSeq[C], b: IndexedSeq[C]) { 
     def run: IndexedSeq[C] = { 
     // special case #1: need to return empty sequence here 
     if (a.size == 0) { 
      return IndexedSeq.empty[C] 
     } 

     // special case #2: need to return original input here 
     if (a == b) { 
      return a 
     } 

     val result = mutable.ArrayBuffer[C]() 

     for (i <- 0 until scala.math.min(a.size, b.size)) { 
      result += a(i) 
      result += b(i) 
     } 
     result.toIndexedSeq 
     } 
    } 
+0

它看起來工作完美無瑕!謝謝! – GreyCat