https://kotlinlang.org logo
#announcements
Title
# announcements
f

Florian

07/08/2019, 10:00 AM
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

diesieben07

07/08/2019, 10:02 AM
You already found it, it's called
iterator
😛
That returns an
Iterator
which you can then traverse using
hasNext
and
next
calls
k

kralli

07/08/2019, 10:10 AM
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

Florian

07/08/2019, 10:25 AM
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

diesieben07

07/08/2019, 10:26 AM
Yes, it is possible. https://pl.kotl.in/ZiaruOtUr
f

Florian

07/08/2019, 10:27 AM
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

diesieben07

07/08/2019, 10:28 AM
val it = (1..10).iterator()
f

Florian

07/08/2019, 10:29 AM
I see
d

diesieben07

07/08/2019, 10:29 AM
And then you have, again, an
Iterator
which you can go through using
for...in
or
hasNext()
and
next()
f

Florian

07/08/2019, 10:30 AM
ok thank you
d

Dico

07/08/2019, 5:59 PM
You can only do
for (i in iterator)
Because the stdlib has
fun Iterator<T>.iterator() = this
f

Florian

07/08/2019, 6:11 PM
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

Ryan Mentley

07/08/2019, 9:47 PM
it's translated to
contains
so yes, you can call it yourself: just call
someObject.contains(someOtherObject)
d

diesieben07

07/09/2019, 7:47 AM
@Florian What do you mean by "doesn't actually replace it in the code"?
f

Florian

07/09/2019, 11:01 AM
@Ryan But I am talking about iteration
It doesn't replace the "in" keyword
d

diesieben07

07/09/2019, 11:10 AM
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

Florian

07/09/2019, 12:28 PM
yea that's what I wanted to clarify
2 Views