2013-10-12 24 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