@@ -967,27 +967,7 @@ object Iterator extends IterableFactory[Iterator] {
967
967
* @tparam A Type of the elements
968
968
* @tparam S Type of the internal state
969
969
*/
970
- def unfold [A , S ](init : S )(f : S => Option [(A , S )]): Iterator [A ] = new AbstractIterator [A ] {
971
- private [this ] var state : S = init
972
- private [this ] var nextResult : Option [(A , S )] = null
973
-
974
- override def hasNext : Boolean = {
975
- if (nextResult eq null ) {
976
- nextResult = Objects .requireNonNull(f(state), " null during unfold" )
977
- state = null .asInstanceOf [S ] // allow GC
978
- }
979
- nextResult.isDefined
980
- }
981
-
982
- override def next (): A = {
983
- if (hasNext) {
984
- val (value, newState) = nextResult.get
985
- state = newState
986
- nextResult = null
987
- value
988
- } else Iterator .empty.next()
989
- }
990
- }
970
+ def unfold [A , S ](init : S )(f : S => Option [(A , S )]): Iterator [A ] = new UnfoldIterator (init)(f)
991
971
992
972
/** Creates an iterator to which other iterators can be appended efficiently.
993
973
* Nested ConcatIterators are merged to avoid blowing the stack.
@@ -1108,6 +1088,31 @@ object Iterator extends IterableFactory[Iterator] {
1108
1088
}
1109
1089
}
1110
1090
1091
+ /** `Iterator` which uses a function `f` to produce elements of
1092
+ * type `A` and update an internal state `S`.
1093
+ */
1094
+ private final class UnfoldIterator [A , S ](init : S )(f : S => Option [(A , S )]) extends AbstractIterator [A ] {
1095
+ private [this ] var state : S = init
1096
+ private [this ] var nextResult : Option [(A , S )] = null
1097
+
1098
+ override def hasNext : Boolean = {
1099
+ if (nextResult eq null ) {
1100
+ nextResult = Objects .requireNonNull(f(state), " null during unfold" )
1101
+ state = null .asInstanceOf [S ] // allow GC
1102
+ }
1103
+ nextResult.isDefined
1104
+ }
1105
+
1106
+ override def next (): A = {
1107
+ if (hasNext) {
1108
+ val (value, newState) = nextResult.get
1109
+ state = newState
1110
+ nextResult = null
1111
+ value
1112
+ } else Iterator .empty.next()
1113
+ }
1114
+ }
1115
+
1111
1116
// scalac generates a `readReplace` method to discard the deserialized state (see https://github.com/scala/bug/issues/10412).
1112
1117
// This prevents it from serializing it in the first place:
1113
1118
private [this ] def writeObject (out : ObjectOutputStream ): Unit = ()
0 commit comments