Scala `view`:` force` is not a member of `Seq`

It seems that applying mapand filtersomehow transforms a viewinto Seq. the documentation contains this example:

> (v.view map (_ + 1) map (_ * 2)).force
res12: Seq[Int] = Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)  

But if I go down something, I get an error message:

> val a = Array(1,2,3)
> s.view.map(_ + 1).map(_ + 1).force
<console>:67: error: value force is not a member of Seq[Int]

It seems that if I'm mapover Array viewmore than once, then it SeqViewbecomes Seq.

> a.view.map(_+1)
res212: scala.collection.SeqView[Int,Array[Int]] = SeqViewM(...)
> a.view.map(_+1).map(_+1)
res211: Seq[Int] = SeqViewMM(...)

I suspect that this behavior may have something to do Arraywith being a mutable collection, as I cannot reproduce this behavior with Listor Vector. However, I can filter Array viewas many times as I like.

+4
source share
1

Pro tip: implicits REPL, reify reflect - .

scala> import reflect.runtime.universe.reify
scala> import collection.mutable._ // To clean up reified exprs
scala> reify(a.view.map(_ + 1).map(_ * 2))
Expr[Seq[Int]](Predef.intArrayOps($read.a).view.map(((x$1) => x$1.$plus(1)))(IndexedSeqView.arrCanBuildFrom).map(((x$2) => x$2.$times(2)))(Seq.canBuildFrom))

IndexedSeqView.arrCanBuildFrom IndexedSeqView, SeqView. , SeqView . , CBF, map, SeqView.canBuildFrom, - Seq. , , SeqView.canBuildFrom .

scala> a.view.map(_ + 1).map(_ * 2)(collection.SeqView.canBuildFrom)
<console>:??: error: polymorphic expression cannot be instantiated to expected type;
 found   : [A]scala.collection.generic.CanBuildFrom[collection.SeqView.Coll,A,scala.collection.SeqView[A,Seq[_]]]
    (which expands to)  [A]scala.collection.generic.CanBuildFrom[scala.collection.TraversableView[_, _ <: Traversable[_]],A,scala.collection.SeqView[A,Seq[_]]]
 required: scala.collection.generic.CanBuildFrom[scala.collection.SeqView[Int,Array[Int]],Int,?]
       a.view.map(_ + 1).map(_ * 2)(collection.SeqView.canBuildFrom)
                                                       ^

, - ; , .

scalac , CBF be Int , , , A, . , , . .

scala> implicitly[collection.SeqView[Int, _] <:< collection.TraversableView[_, _]]
<function1>

Array[Int] <: Traversable[_]. . Array Traversable, Seq CBF Seq.

, SeqView arrCanBuildFrom IndexedSeqView. . Array; , Array ( Traversable) .

+3

Source: https://habr.com/ru/post/1660349/


All Articles