Are inline functions like `forEach`, `forEachIndex...
# announcements
v
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
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
Why would you want to mock that? You can't mock for either?
Oh well, I'm to slow.
v
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
You can mock the Iterable. In both languages and mocking libraries
v
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
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
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
@v79 can you share the code your testing?
f
@v79 What is the advantage of mocking
forEach
vs mocking at a higher level ?
v
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
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.