I am trying to create a wrapper of List
with a specific type (e.g. List[Int]
) such that methods that take an implicit CanBuildFrom
parameter return an instance of my wrapper instead of List
.
One possible solution, which feels rather heavyweight, is:
import scala.collection._
import generic.{CanBuildFrom, SeqForwarder}
import mutable.{Builder, ListBuffer}
class MyList(list: List[Int]) extends immutable.LinearSeq[Int]
with LinearSeqLike[Int, MyList]
with SeqForwarder[Int] {
override def newBuilder: Builder[Int, MyList] = MyList.newBuilder
protected override def underlying = list
}
object MyList {
def newBuilder: Builder[Int, MyList] =
new ListBuffer[Int] mapResult(new MyList(_))
implicit def canBuildFrom: CanBuildFrom[MyList, Int, MyList] = {
new CanBuildFrom[MyList, Int, MyList] {
def apply(from: MyList) = from.newBuilder
def apply() = newBuilder
}
}
}
val l1 = new MyList(List(1,2,3))
println(l1.isInstanceOf[MyList])
println(l1.map(_ + 1).isInstanceOf[MyList])
println(l1.filter(_ == 2).isInstanceOf[MyList])
Is there a better/easier way to create such a wrapper or did I miss anything important in the implementation of MyList
?
Edit: A follow-up question is: Can this whole wrapper logic be put into ListWrapper
classes or traits so that the above MyList
can be implemented like this:
class MyList extends ListWrapper[Int, MyList]
object MyList extends ListWrapperFactory[Int, MyList]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…