# For vs forEach

**URL:** <https://discuss.kotlinlang.org/t/for-vs-foreach/2556>\
**Category:** Uncategorized\
**Created:** [May 8, 2017, 4:06am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556 "2017-05-08T04:06:06Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 8, 2017, 4:06am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/1 "2017-05-08T04:06:06Z")

</div>

In the classic iterative factorial function you can do:

```
var total = one
(two rangeTo x).forEach{i -> total *= i}

```

or

```
var total = one
for (i in two rangeTo x) { total *= i }

```

(Seemingly a bit weird code due to using BigInteger – Integer and Long are simply not up to the task of calculating factorials.)

Which of these Kotlin statements is deemed more idiomatic?

(Is the Kotlin equivalent of Python’s Pythonic, Kotlinic?)

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [May 8, 2017, 7:51am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/2 "2017-05-08T07:51:27Z")

</div>

This was discussed here: [for vs forEach · Issue #33 · Kotlin/kotlin-style-guide · GitHub](https://github.com/yole/kotlin-style-guide/issues/33)  
In this case, I’d definitely go for `for`.

(Also, you don’t need to invoke `rangeTo` as a method; you should use the `..` operator instead.)

---

<div class="post-metadata">

**Author:** ![jstuyts](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/jstuyts/32/2141_2.png) [@jstuyts](https://discuss.kotlinlang.org/u/jstuyts)\
**Post date:** [May 8, 2017, 7:54am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/3 "2017-05-08T07:54:25Z")

</div>

You are folding the collection. The example below uses integers:

```
val total = (2..x).fold(1) { total, value -> total * value }

```

---

<div class="post-metadata">

**Author:** ![douglarek](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/douglarek/32/2088_2.png) [@douglarek](https://discuss.kotlinlang.org/u/douglarek)\
**Post date:** [May 8, 2017, 7:58am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/4 "2017-05-08T07:58:31Z")

</div>

Any way, if I do more than one thing, I will choose `for`; `forEach` is just a method reference or side effect change

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 8, 2017, 8:34am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/5 "2017-05-08T08:34:25Z")

</div>

I am not convinced myself about not using forEach, but if using for is the preferred style, I have no problem.

I believe I do need the rangeTo since … is not defined for BigInteger and I therefore have to define a rangeTo operator.

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 8, 2017, 8:35am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/6 "2017-05-08T08:35:45Z")

</div>

I actually have that solution as well. This is a collection of different algorithms achieving the same goal I have the fold version, my question was the most idiomatic representation of the iterative version.

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [May 8, 2017, 8:46am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/7 "2017-05-08T08:46:36Z")

</div>

Defining the rangeTo operator is what allows you to use `..`

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 8, 2017, 8:48am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/8 "2017-05-08T08:48:13Z")

</div>

Using rangeTo works, but if I use … I get a “For-loop range must have an iterator() method”. So I guess my support code is missing something.

---

<div class="post-metadata">

**Author:** ![alanfo](https://avatars.discourse-cdn.com/v4/letter/a/bbe5ce/32.png) [@alanfo](https://discuss.kotlinlang.org/u/alanfo)\
**Post date:** [May 8, 2017, 5:58pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/9 "2017-05-08T17:58:05Z")

</div>

I generally prefer to use ‘for’ unless I don’t need a control variable in the body when I use forEach instead.

On your last point, ‘Pythonic’ is already an English word whereas ‘Kotlinic’ is not and so the former ‘sounds right’ to me but the latter does not.

As a portmanteau word, I think I prefer ‘Kotlinesque’ to ‘Kotlinic’.

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 8, 2017, 6:24pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/10 "2017-05-08T18:24:50Z")

</div>

The downside of Kotlinesque would be that Pythonesque is a very negative description: Pythonic – your code is in harmony with the Python infrastructure; Pythonesque – your code has the look and feel of a series of Monty Python’s Flying Circus.

---

<div class="post-metadata">

**Author:** ![alanfo](https://avatars.discourse-cdn.com/v4/letter/a/bbe5ce/32.png) [@alanfo](https://discuss.kotlinlang.org/u/alanfo)\
**Post date:** [May 8, 2017, 8:14pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/11 "2017-05-08T20:14:38Z")

</div>

I think I’m right in saying that Guido van Rossum named his language after Monty Python’s Flying Circus so Pythonistas might not necessarily object to ‘Pythonesque’ to describe the language’s idioms. In fact, according to [this link](https://en.wiktionary.org/wiki/Pythonesque) the word is sometimes used in this sense.

Perhaps we don’t really need an adjective for Kotlin in any case. Running through a list of the most popular languages (Java, C, C++, C#, JavaScript etc.) I can’t think of a suitable adjective for any of them.

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [May 9, 2017, 6:46am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/12 "2017-05-09T06:46:40Z")

</div>

During my Python workshops I used Pythonic as good and Pythonesque as bad to instil in people a sense of being idiomatic and in sympathy with the language and underlying runtime. Maybe I was abusing the term Pythonesque, but it worked for the audience.

The languages you mentioned are all old languages and suffer from style wars and thus doubt and uncertainty. Also a lot of poor code. Languages such as Go, Rust, Ceylon, etc. try to encourage (well Go totally enforces) a single style of code that everyone will use. This avoids style wars. Also as a side effect it makes it a lot harder to write non-idiomatic code. This I think is a good thing. Whilst I have lots of disagreements with the one-and-only Go format style, that there is only one removes a whole collection of decisions a programmer has to consider. So Go removes a whole dimension of style, and thus a whole dimension of idiomatic.

Anyway, in one sense you are totally right “idiomatic” serves for all languages. It is nice though that “idiomatic Python” can be shortened to Pythonic.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [May 11, 2017, 8:03pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/13 "2017-05-11T20:03:55Z")

</div>

Might also want to consider tail recursion as an alternative:

```
val BigInteger.factorial : BigInteger
    get()
    {
        tailrec fun factorial(n: BigInteger, total:BigInteger) : BigInteger
            = if(n > BigInteger.ONE)
            	factorial(n - BigInteger.ONE, total * n)
            else
                 total
        
        return factorial(this, BigInteger.ONE)
    }

```

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [October 14, 2018, 7:53am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/14 "2018-10-14T07:53:11Z")

</div>

Apologies for seeming to disappear for over a year.

Tail recursion clearly beats recursion in this situation, but iterative with reduce/fold or for loop still wins performance wise – at least with the slightly unscientific measures I have.

You example is though really helpful since I should always have done the examples as extension methods on `BigInteger`!

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [October 15, 2018, 6:57pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/15 "2018-10-15T18:57:41Z")

</div>

> [@dalewking](#):
>
> val BigInteger.factorial : BigInteger get() { tailrec fun factorial(n: BigInteger, total:BigInteger) : BigInteger = if(n \> BigInteger.ONE) factorial(n - BigInteger.ONE, total \* n) else total return factorial(this, BigInteger.ONE) }

Took a look at what gets generated and it looks like what is hurting it performance wise is that it keeps checking for nulls because it doesn’t realize that BigInteger subtraction and multiplication calls will not return null. Don’t know if the new contracts stuff will help with that. It is even checking BigInteger.ONE to make sure it is not null each time.

---

<div class="post-metadata">

**Author:** ![Russel](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/russel/32/1442_2.png) [@Russel](https://discuss.kotlinlang.org/u/Russel)\
**Post date:** [October 16, 2018, 7:23am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/16 "2018-10-16T07:23:55Z")

</div>

Seems like some work here might be useful. `BigInteger` and `BigDecimal` are critical a lot of calculations in bioinformatics, finance, etc. Python, R, and Julia are the incumbents in this space and without performance Kotlin will not compete.

---

<div class="post-metadata">

**Author:** ![fvasco](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fvasco/32/1961_2.png) [@fvasco](https://discuss.kotlinlang.org/u/fvasco)\
**Post date:** [October 16, 2018, 10:35am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/17 "2018-10-16T10:35:13Z")

</div>

> [@dalewking](#):
>
> Took a look at what gets generated and it looks like what is hurting it performance wise is that it keeps checking for nulls because it doesn’t realize that BigInteger subtraction and multiplication calls will not return null. Don’t know if the new contracts stuff will help with that. It is even checking BigInteger.ONE to make sure it is not null each time.

JVM compiler can remove null checks and dead code, JVM bytecode is really far to C2 output.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [October 16, 2018, 1:49pm UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/18 "2018-10-16T13:49:04Z")

</div>

> [@fvasco](#):
>
> JVM compiler can remove null checks and dead code, JVM bytecode is really far to C2 output.

It CAN, but would be much better to not have to put them there in the first place.

---

<div class="post-metadata">

**Author:** ![pdvrieze](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/pdvrieze/32/1882_2.png) [@pdvrieze](https://discuss.kotlinlang.org/u/pdvrieze)\
**Post date:** [October 17, 2018, 11:19am UTC](https://discuss.kotlinlang.org/t/for-vs-foreach/2556/19 "2018-10-17T11:19:39Z")

</div>

There is a compiler option to disable all the null checks. Perhaps it would be worthwhile to have an annotation that can disable it on a smaller scale. Of course in some cases the explicit null checks can actually speed things up as the jit doesn’t need to be as careful afterwards.
