Hacker News new | past | comments | ask | show | jobs | submit login

it looks exactly like Java's peek(), not sure why they don't use the same naming.



It is not like java peek at all (or I am missing what peek do your refer to).

Peek is to get the reference of the first element. OnEach makes a lazy operation for every element on the sequence. I would say that onEach is more like map but lazy.


It's just forEach that returns the collection/sequence instead of returning Unit. Don't overthink it. It's not like map.


> On iterables it behaves like forEach but also returns the iterable instance further. And on sequences it returns a wrapping sequence, which applies the given action lazily as the elements are being iterated.

like forEach and also returns the iterable instance or like map, it is the same.

For me the key thing is that onEach applies lazily for sequences.


No, it's not like map.

Map builds a new collection based on the function you provide it. At the end of a map call you end up with a potentially transformed collection instance.


You should consider change your tone when you talk to people. It is quite rude.

It is not a map and it is not a forEach, that is why they created it.

> At the end of a map call you end up with a potentially transformed collection instance

The difference between onEach and map is that map returns a new collection that can have different type of elements. But onEach can modify the internal state of the objects when applied. Also onEach is lazy and map is not lazy in kotlin (as far as I know).

Why did I make the comparison with map and not with forEach? Because forEach is basically a translation of a for and map is a functional function and onEach it is also a functional function. You can agree or disagree with my way of trying to explain things, but being rude in your comments saying you are not right (when I know) and them providing another solution that you also know it isn't right, feels like a troll comment.


May I describe it as an effectful identity ?


It is not an identity because you can modify the internal state of the objects. And it is also lazy:

arrayOf("A","B","C").onEach{ print("onEach $it")}.forEach{ print("forEach $it")}

prints:

onEach A forEach A onEach B forEach B onEach C forEach C


thanks


Java's stream has a peek(), which also makes a lazy operation for every element in the stream.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: