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

v79

08/11/2019, 6:59 AM
Are inline functions like
forEach
,
forEachIndex
,
File.walk()
just syntactic sugar that I can use instead of
(for x in y)
or should I be much for careful when using them? I've discovered that
forEach
cannot be mocked with a library like mockk and that's playing havoc with my testing.
h

Hanno

08/11/2019, 7:04 AM
You really need to mock an iteration? Hell, it's getting out of control :D how would you mock (for x in y) though??
s

SiebelsTim

08/11/2019, 7:04 AM
Why would you want to mock that? You can't mock for either?
Oh well, I'm to slow.
v

v79

08/11/2019, 7:06 AM
It's straightforward to mock a Java Iterator in Mockito so it's not so had to mock a Java
for(int x : y)
, isn't it?
s

SiebelsTim

08/11/2019, 7:09 AM
You can mock the Iterable. In both languages and mocking libraries
v

v79

08/11/2019, 7:17 AM
I think my app needs a massive refactoring to make it testable! Though my original question still stands - should I use
forEach
liberally, instead of the
for
loop, or only in a few specific scenarios?
s

SiebelsTim

08/11/2019, 8:07 AM
I think it's mostly the same, except a few corner cases for example regarding ranges if I remember correctly. I would use for whenever it fits. I use forEach usually when it's a longer chain. Also see https://kotlinlang.org/docs/reference/coding-conventions.html#using-loops
l

Leon K

08/11/2019, 10:31 AM
they mostly get inlined, altough it is recommended to use regular
for
loops as long as its not as part of a chain ;D Using `map`/`reduce` is recommended though
t

Tim Schraepen

08/11/2019, 11:02 AM
@v79 can you share the code your testing?
f

Frank Harper

08/11/2019, 3:28 PM
@v79 What is the advantage of mocking
forEach
vs mocking at a higher level ?
v

v79

08/12/2019, 5:29 PM
I'd be ashamed to share my code, there was about 150 lines of code inside that
forEach
block. It's prompted some long-overdue refactoring.
t

Tim Schraepen

08/13/2019, 12:37 PM
You should never be ashamed of learning opportunities! I didn’t want to shame you or your code, but it can be really helpful for other people to learn from. Now you can share your code before and after your refactoring! I understand if you don’t feel comfortable sharing your code.
2 Views