Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 247 Vote(s) - 3.63 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Does Kotlin have an "enumerate" function like Python?

#1
In Python I can write:

for i, element in enumerate(my_list):
print(i) # the index, starting from 0
print(element) # the list-element

How can I write this in Kotlin?
Reply

#2
There is a [`forEachIndexed`](

[To see links please register here]

) function in the standard library:

myList.forEachIndexed { i, element ->
println(i)
println(element)
}

See [@s1m0nw1's answer](

[To see links please register here]

) as well, `withIndex` is also a really nice way to iterate through an `Iterable`.
Reply

#3
### Iterations in Kotlin: Some Alternatives
Like [already][1] said, `forEachIndexed` is a good way to iterate.

**Alternative 1**

The extension function `withIndex`, defined for `Iterable` types, can be used in `for`-each:

val ints = arrayListOf(1, 2, 3, 4, 5)

for ((i, e) in ints.withIndex()) {
println("$i: $e")
}

**Alternative 2**

The extension property `indices` is available for `Collection`, `Array` etc., which let's you iterate like in a common `for` loop as known from C, Java etc:

for(i in ints.indices){
println("$i: ${ints[i]}")
}


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through