それを行うための1つのクリーンな方法は、エクストラクタを定義+:
し:+
て自分で使用することです:
object +: {
def unapply[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): Option[(A, That)] = {
if (seq.nonEmpty)
Some(seq.head, cbf(seq) ++= seq.tail result)
else
None
}
}
object :+ {
def unapply[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): Option[(That, A)] = {
if (seq.nonEmpty)
Some(cbf(seq) ++= seq.dropRight(1) result, seq.last)
else
None
}
}
次に、次のように簡単に実行できます。
val x = Seq(1, 2, 3, 4)
val first +: middle :+ last = x
println("first is %s".format(first))
for (y <- middle)
println("middle contains %s".format(y))
println("last is %s".format(last))
どちらが印刷されますか:
first is 1
middle contains 2
middle contains 3
last is 4