Most operators can be called in their function for...
# announcements
f
Most operators can be called in their function form, like
1.plus(2)
. Is there also a form like this for
in
when it uses
iterator
(not
contains
)?
d
You already found it, it's called
iterator
😛
That returns an
Iterator
which you can then traverse using
hasNext
and
next
calls
k
As Take correctly said,
in
stands for
iterator()
. So what exactly are you trying to achieve?
If you are looking for a different way to loop, then
iterator.forEach { }
might be a solution.
f
I mean that you can use the other operators in their function form
but for iterator this doesnt seem possible
its a theoretical question
d
Yes, it is possible. https://pl.kotl.in/ZiaruOtUr
f
I mean directly in this construct
(i in 1..10)
you cant call i.iterator(1..10) or something like that
other operators can be replaced directly like this
1 + 2 -> 1.plus(2)
1..10 -> 1.rangeTo(10)
d
val it = (1..10).iterator()
f
I see
d
And then you have, again, an
Iterator
which you can go through using
for...in
or
hasNext()
and
next()
f
ok thank you
d
You can only do
for (i in iterator)
Because the stdlib has
fun Iterator<T>.iterator() = this
f
yea thats what I mean, it's a bit different because Ctrl+B on
in
brings me to the iterator function
but it doesn't actually replace it in the code
r
it's translated to
contains
so yes, you can call it yourself: just call
someObject.contains(someOtherObject)
d
@Florian What do you mean by "doesn't actually replace it in the code"?
f
@Ryan But I am talking about iteration
It doesn't replace the "in" keyword
d
The
for...in
construct compiles to several method calls: One call to
iterator
and then a while loop that repeatedly calls
next
until
hasNext
returns false.
The
in
cannot be replaced by just a single method call.
f
yea that's what I wanted to clarify