0

When upgrading the scala version of an existing code base the build warns that the .toIterable method on an Iterator is deprecated.

How can an Iterator be converted to an Iterable in Scala 2.13?

Intellij recommends

use .iterator.to(Iterable)

However, the .iterator seems redundant.

Thank you in advance for your consideration and response.

Ramón J Romero y Vigil
  • 17,373
  • 7
  • 77
  • 125
  • 3
    Are you sure you want any arbitrary iterable? That may change order, lose elements, have extremely bad performance for the following operations, etc; I would pick a concrete collection like `toList`, but if you are ok with whatever you can just call `to(Iterable)` – Luis Miguel Mejía Suárez Mar 31 '21 at 21:06
  • maybe try reading that warning to the end? ;) – Dima Mar 31 '21 at 21:12
  • @LuisMiguelMejíaSuárez `.toList` is also deprecated :) – Dima Mar 31 '21 at 21:14
  • 2
    @Dima ahm no, it isn't: https://www.scala-lang.org/api/current/scala/collection/Iterator.html#toList:List[A] there is an overload version that is deprecated tho. – Luis Miguel Mejía Suárez Mar 31 '21 at 21:16
  • @dima Luis is correct. He meant using `to(Iterable)` directly without calling `.iterator`. Also I recommend just use `toList` directly because `Iterable`'s factory is just a delegate of List so `to(Iterable)` will give you a List anyway: https://github.com/scala/scala/blob/v2.13.5/src/library/scala/collection/immutable/Iterable.scala#L32 – SwiftMango Apr 01 '21 at 02:19
  • @texasbruce yeah, I dunno. Intelling me `toList` is deprecated to and suggests `to(List)`, which kinda makes sense. It looks like there's really two of them (which is another reason not to use it if you ask me) ... In any event, I think using `toList` or `to(List)` when you just need an iterable, is a bad practice in the first place: one should always be using the most abstract interface that fits the need. – Dima Apr 01 '21 at 10:55

1 Answers1

2

Generally,

   val v: Iterator[Int] = ???
   val vv = v.to(Iterable)

but if you need more than one iteration

   val v: Iterator[Int] = ???
   val vv: Iterable[Int] = v.to(List)
Iva Kam
  • 932
  • 4
  • 13