Is there any stdlib kind of Iterator that allows t...
# announcements
c
Is there any stdlib kind of Iterator that allows to “go back” (like .previous()) or at least “see” the next element without actually calling .next() and therefore making it advance?
d
List iterators allow that iirc.
The going back I mean.
Peeking is not part of the Java iterator API sadly.
c
That's a shame—I kinda need to do that with a sequence and I don't want it to calculate all the elements (cause I presume to make a list iterator I'd need a list)
d
Yeah you'd need a a list.
You could keep track of the previous element or maybe
zip
might help?
t
That's right. ListIterator defined a
previous()
function. Peeking (looking at the next element without progressing) is not included, which might be a good thing because in some cases it could lead to unexpected behaviour. However, you could implement your own "PeakingIterator" (or use the one from apache commons if you're on JVM)
n
@Chilli if you need to provide a peek function that's relatively straightforward, I think, or at least more straighforward than anything else discussed
basically all you need is an iterator that buffers one element
c
True, I think I'll try making one myself so I don't need a list nor any extra library
t
Of course there are multiple ways to implement that. This is a kotlinized version of the Google/Guava implementation (com.google.common.collect.Iterators.PeekingImpl)
n
Did you have it written with "Peak" everywhere a second ago? lol otherwise i may be having a stroke
o
He will never tell :)))
t
note that this implementation will fail if you call
peek()
and there are no more elements. A check for that could be added easily if you want that behaviour @Nir you're not having a stroke (I hope), I just had a brain fart when writing the class
n
Okay, I started a comment pointing that out and then it changed with no "modified" thing in slack, phew
I agree with the basic idea of the implementation but I'm not sure I agree with the boolean and branching
I'd probably just implement it by always being one step ahead, seems simpler
t
Yeah, I'm not so shure about that either. My first thought was basically copying Kotlin's own
AbstractIterator
implementation and exposing
nextValue
(or something that would look very similar). I wouldn't have written it like above myself, but it is shorter and part of a widely used Google lib, it should be ok.
Somehow Slack doesn't seem to mark edited text snippets as modified. Now I'm wondering, what would a "PeakingIterator" look like 🤔
n
Copy code
class PeekingIterator<T>(private val iterator: Iterator<T>) : Iterator<T> {
    
    fun Iterator<T>.nextOrNull() = if (iterator.hasNext()) iterator.next() else null
    
    var nextElement = iterator.nextOrNull()

    override fun hasNext() = (nextElement != null)

    override fun next(): T {
        val next = nextElement!!
        nextElement = iterator.nextOrNull()
        return next
    }

    fun peek() = nextElement
}
t
should work for most cases, but you should limit the generic Parameter to
PeakingIterator<T: Any>
(not allowing nullable types). Having null values would break this implementation
n
that's a great point
t
and if you want to be pedantic, do
Copy code
override fun next(): T {
        val next = nextElement ?: throw NoSuchElementException()
...
1
n
hmm this is the second time recently in Kotlin that I've wanted a "private" nullable, if that makes sense
a nullable type where I'm the only one that can null it, and the "non-null state" can hold a null itself. If that makes sense.
I guess some sort of Optional<T> like thing, which would allow you to have Optional<Int?> if you so wanted for instance
t
I know what you mean, had the same thought in my work project this week. Basically i want what JS has - a distinction between
null
and
undefined
n
the thing about Kotlin which is a bit weird now that I think of it is that Kotlin effectively collapses nulls
t
There was a question here yesterday about passing
null
for an optional parameter that also has
null
as its default value. Same issue.
n
typically in languages with generics, and something like optional, it doesn't work that way
e.g. in C++, you have optional<T>, T itself can be say optional<int>, and then the outer type is optional<optional<int>>
not very useful in non-generic code, ok, but it is quite useful in generic code like this
t
I mean you could do the same in Kotlin, you just usually wouldn't. I think we just got so used to Kotlin's null-handling (and we love it) that we forget that - sometimes -
null
can actually be an expected value.
And if that's the case, you can't use null-handling anymore to controll your flow, which you got used to by using
?.let
,
?:
, etc.
Sorry btw to anyone else who still get's notified for messages in this thread
1
n
yeah the thing is that in generic code it can quite happen. Which IMHO really actually limits Kotlin's null usefullness in generic code
*quite easily happen
t
I think I know what you mean. But I think in Kotlin you are actually able to handle that combination quite well. You can limit generic types to lock out nullable types and it you don't want that, you might be more aware of it and just implement it in a way where you don't use null for flow control (e.g. by using Optional-like wrappers). Something like Java is much worse, because you basically have no idea if something might be null.
n
yeah the Java situation is definitely crazy, don't get me wrong.