考慮以下自定義Seq
工作:如何在Scala中創建具有有界類型參數的自定義Seq?
class MySeq[B](val s: Seq[B])
extends Seq[B]
with GenericTraversableTemplate[B, MySeq]
with SeqLike[B, MySeq[B]] {
override def companion = MySeq
def iterator = s.iterator
def apply(i: Int) = s(i)
def length = s.length
override def toString = s map { _.toString } mkString("\n")
}
object MySeq extends SeqFactory[MySeq] {
implicit def canBuildFrom[B]: CanBuildFrom[Coll, B, MySeq[B]] =
new GenericCanBuildFrom[B]
def newBuilder[B] = new ListBuffer[B] mapResult (x => new MySeq(x.toSeq))
}
我想強加約束的類型參數B
。換句話說,我想這樣的事情(不工作):
class MyA
class MySeq[+B <: MyA](val s: Seq[B])
extends Seq[B]
with GenericTraversableTemplate[B, MySeq]
with SeqLike[B, MySeq[B]] {
override def companion = MySeq // Type Mismatch Here
def iterator = s.iterator
def apply(i: Int) = s(i)
def length = s.length
override def toString = s map { _.toString } mkString("\n")
}
object MySeq extends SeqFactory[MySeq] {
implicit def canBuildFrom[B]: CanBuildFrom[Coll, B, MySeq[B]] =
new GenericCanBuildFrom[B]
// Type Mismatch in the line below
def newBuilder[B] = new ListBuffer[B] mapResult (x => new MySeq(x.toSeq))
}
但我得到的指示線以下類型不匹配錯誤:
inferred type arguments [B] do not conform to
class MySeq's type parameter bounds [+B <: MyA]
Main.scala line 49
type mismatch;
found : countvotes.structures.MySeq.type
required: scala.collection.generic.GenericCompanion[Seq]
Main.scala line 36
type mismatch;
found : MySeq[B(in class MySeq)]
required: MySeq[B(in method newBuilder)]
Main.scala line 49
type mismatch;
found : scala.collection.immutable.Seq[B(in method newBuilder)]
required: Seq[B(in class MySeq)]
Main.scala line 49
我曾試圖解決這個問題將邊界添加到CanBuildFrom和newBuilder的類型參數中,但隨後出現其他錯誤消息。
如何創建一個自定義Seq
並綁定了一個類型參數?
你而擴展集合然後在包裝類與上限要求封裝它的任何理由? –
原因是它會更優雅。我會在這堂課上使用'map'和'filter',每次手動解包和重新包裝都會很不方便。 – Bruno